iOS小技能: 日历的使用(案例:两个时间的比较、获取最近30天的数据)

704 阅读4分钟

“我正在参加「掘金·启航计划」”

引言

预备知识:日历标识符NSCalendarIdentifier

         NSCalendarIdentifierGregorian         //公历
         NSCalendarIdentifierBuddhist          //佛_教日历
         NSCalendarIdentifierChinese           //中_国农历
         NSCalendarIdentifierHebrew            //希_伯来日历
         NSCalendarIdentifierIslamic           //伊_斯兰日历
         NSCalendarIdentifierIslamicCivil      //伊_斯兰教日历
         NSCalendarIdentifierJapanese          //日_本日历
         NSCalendarIdentifierRepublicOfChina   //中_华民_国日历(台湾)
         NSCalendarIdentifierPersian           //波_斯历
         NSCalendarIdentifierIndian            //印_度日历
         NSCalendarIdentifierISO8601           //ISO8601

I 日历的使用

1.1 两个时间的比较(NSDateComponents)

案例1: 计算两个时间的间隔(天)

/**
 计算两个时间的间隔(天)
 
 @param start 开始时间
 @param end 结束时间
 @return 间隔时间
 */
+ (NSInteger)contrastTimeBackDayWithStartDate:(NSString *)start endDate:(NSString *)end
{
    NSTimeInterval time = [self contrastTimeWithyyyyMMddStartDate:start endDate:end];
    NSInteger minute,second,hour,day;
    second=(NSInteger)time%1000;
    minute = (NSInteger)(time/60)%60;
    hour = (NSInteger)(time/3600)%24;
    day = (time/3600/24);
    return day;
}

/**
 计算两个时间的间隔(毫秒)
 
 @param start 开始时间
 @param end 结束时间
 @return 间隔时间
 */
+ (NSTimeInterval)contrastTimeWithyyyyMMddStartDate:(NSString *)start endDate:(NSString *)end
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];

    
    NSDate *startDate = [dateFormatter dateFromString:start];
    NSDate *endDate = [dateFormatter dateFromString:end];
    NSTimeInterval time = [endDate timeIntervalSinceDate:startDate];
    return time;
}

案例2:处理微博的发布时间

/**
 处理今年的时间
 */
- (NSString*)setupDateInThisYear:(NSDate*)tmpDate{
    NSCalendarUnit calendarUnit = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute;
    NSDateComponents *dateComponents = [self dateComponentsWithFromDate:tmpDate toDate:[NSDate date] calendarUnit:calendarUnit];
    if ([self isToday:dateComponents]) {
        /**1》一天之内的时间处理*/
        return [self setupTodayTime:dateComponents];
    }else if ([self isYesterDay:dateComponents]){
        /*2》25-48小时后的时间处理(24小时之后)
         yesterday HH:mm  yesterday 17:30  两天之内 (48小时之内)25-48小时之内*/
        return [NSString stringWithFormat:@"yesterday %@",[self stringFromDate:tmpDate dateformatter:@"HH:mm" localeIdentifier:@"en_US"]];
    }else{
        /*3》48小时后的时间处理(其它时间)
         MM-dd HH:mm  09-18 17:30      48小时之后*/
        return [self stringFromDate:tmpDate dateformatter:@"MM-dd HH:mm" localeIdentifier:@"en_US"];
    }

}

1.2 时间获取

iOS 获取时间的应用场景: 报表的时间筛选

  1. 获取上个月 self.viewModel.multipleSwitchCellTableViewCellModel.MonthlyDateStr = [QCT_Common strdate4lastMonthlyStrYYMM];
/**
 获取上个月份字符串
 */
+ (NSString *)strdate4lastMonthlyStrYYMM{    
    NSDate *currentDate = [NSDate date];
        
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
        NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
    //    [lastMonthComps setYear:1]; // year = 1表示1年后的时间 year = -1为1年前的日期,month day 类推
        [lastMonthComps setMonth:-1];
        NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
    
    

    NSString *tmpbirthday = @"";
    tmpbirthday  = [QCT_Common date4YYMM:newdate];
            NSLog(@"date str = %@", tmpbirthday);
    //    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //        [formatter setDateFormat:@"yyyy-MM"];
        //        NSString *dateStr = [formatter stringFromDate:newdate];

    return tmpbirthday;
}


  1. 获取本月
/**
 获取当前月份字符串
 */
+ (NSString *)strdate4TodaydateMonthlyStrYYMM{
    
    
    
    NSDate *lastDay =[NSDate date];//
    
//    NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:[NSDate date]];//前一天

    
    

    NSString *tmpbirthday = @"";

    tmpbirthday  = [QCT_Common date4YYMM:lastDay];
    
    return tmpbirthday;
    
}

  1. 获取前一天
+ (NSString *)strdate4lastDayYYMMDD{
    
    NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:[NSDate date]];//前一天
    
    

    NSString *tmpbirthday = @"";

    tmpbirthday  = [QCT_Common date4YYMMDD:lastDay];
    
    return tmpbirthday;

    
}

  1. 获取30天前的日期

使用日历NSCalendar获取时间:根据日期组件NSDateComponents的参数配置获取日期时间- (NSDate *)dateByAddingComponents:(NSDateComponents *)comps toDate:(NSDate *)date options:(NSCalendarOptions)opts;

/**
 获取30天前的日期:格式YY-MM-DD 2022-08-06
 */
+ (NSString *)strdate4lastMonthlyStrYYMMDD{
    
    NSDate *currentDate = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
    //    [lastMonthComps setYear:1]; // year = 1表示1年后的时间 year = -1为1年前的日期,month day 类推
    //        [lastMonthComps setMonth:-1];
    [lastMonthComps setDay:-30];
    NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
    NSString *tmpbirthday = @"";
    tmpbirthday  = [QCT_Common date4YYMMDD:newdate];
    NSLog(@"date str = %@", tmpbirthday);//date str = 2022-08-06
    return tmpbirthday;
}

II 案例

2.1 构造退款单号

商户退款单号(商户退款单号,32个字符内、可包含字母,确保在商户系统唯一。同个退款单号多次请求,平台当一个单处理,只会退一次款。如果出现退款不成功,请采用原退款单号重新发起,避免出现重复退款。)

商户退款单号(out_refund_no):yyMMddHHmmss + xxxxxx(sid)+ 递增序号(隔天重置)

- (NSString *)out_refund_no{
    
    
    NSMutableString *str = [[NSMutableString alloc]initWithString: [QCT_Common getyyMMddHHmmss4TodayTime]];
    [str appendString:xxx.id];   
    [str appendString:QCTSession.shareQCTSession.snid];
    

    
    
    return str;
    
    
    
    
}

  • snid(递增序号(隔天重置))

/**
 yyMMddHHmmss + xxxxxx(6位sid)+ 5位序号

 */
- (NSString *)snid{
    
    
    // 先从偏好获取对象,如果不存在就进行存储
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *k_sndi_keydic = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] dataForKey:k_sndi_key]];
    
    
     
    NSString *str =@"00000";
    
    

    
    NSString *todayStr =     [QCT_Common  date4YYMMDD:[NSDate date]];
    
                              
                              
                              
                              
                              

    if([k_sndi_keydic.allKeys containsObject:k_sndi_date_key]){
        
        
        
        NSString *lastday = k_sndi_keydic[k_sndi_date_key];
        
        
        str = [[NSMutableString alloc]initWithString: k_sndi_keydic[k_sndi_key]];
        
        
        
        

        
        if([todayStr isEqualToString:lastday]){
            
            int d = [str intValue]+1;
            
            
            NSNumber *t = [NSNumber numberWithInt:d];
            
            
            
            
            str =  [QCT_Common addComplementspaces:t.description count:5 placeholder:@"0" isdirectionRight:NO];//
            
            
            
        }else{
            
            
            
            str = @"00000";
            [k_sndi_keydic setValue:todayStr forKey:k_sndi_date_key];


            
            
            
        }
        
        
        
        
        
        
        
        
    }else{
        
        k_sndi_keydic = [NSMutableDictionary dictionary];
        
        
        [k_sndi_keydic setValue:todayStr forKey:k_sndi_date_key];
        
        str = @"00000";
        
        
        
        
        
    }
                              
    
    
    [k_sndi_keydic setValue:str forKey:k_sndi_key];
    
    
    
                              NSData *data  = [NSKeyedArchiver archivedDataWithRootObject: k_sndi_keydic];
                              
                              
                              
                              
                              [user setValue:data forKey:k_sndi_key];
                              
                              [user synchronize];

    
    
    
    NSLog(@"str:%@",FMSTR(@"%@",str));//02022
    
    
    
    return  str;
    
}


kunnan.blog.csdn.net/article/det…

/**
 
 
 str: 原字符串
 count: 补齐到第几位
 
 placeholder: 补齐的符号

 isdirectionRight: 是否往右补齐
 */
+ (NSString*)addComplementspaces:(NSString*)str count:(NSInteger)count  placeholder:(NSString*)placeholder isdirectionRight:(BOOL)isdirectionRight{
    
    
    
    NSLog(@"addComplementspacesstr:%@",FMSTR(@"%@",str));//02022

    
    if (str.length>=count) {
        
        return str;
        
    }
    
    
    
    NSMutableString *tmp = [NSMutableString new];
    
    if(isdirectionRight){
        
        tmp = [[NSMutableString alloc]initWithString:str];// 右补齐
        
        
    }
    
    
    NSInteger tmpcount = count -str.length;
    
    for (int i =0; i< tmpcount; i++) {
        
        [tmp appendString:placeholder];// 补齐
        
        
    }
    
    if(!isdirectionRight){
        [tmp appendString:str];//  往左补齐

    }
    
    NSLog(@"addComplementspacesstr:%@",FMSTR(@"%@",tmp.description));//02022
    

    return tmp.description;
    
}


2.2 计算两个时间的间隔(天)

工具方法:计算两个时间的间隔(天)

/**
 计算两个时间的间隔(天)
 
 @param start 开始时间
 @param end 结束时间
 @return 间隔时间
 */
+ (NSInteger)contrastTimeBackDayWithStartDate:(NSString *)start endDate:(NSString *)end
{
    NSTimeInterval time = [self contrastTimeWithyyyyMMddStartDate:start endDate:end];
    NSInteger minute,second,hour,day;
    second=(NSInteger)time%1000;
    minute = (NSInteger)(time/60)%60;
    hour = (NSInteger)(time/3600)%24;
    day = (time/3600/24);
    return day;
}

/**
 计算两个时间的间隔(毫秒)
 
 @param start 开始时间
 @param end 结束时间
 @return 间隔时间
 */
+ (NSTimeInterval)contrastTimeWithyyyyMMddStartDate:(NSString *)start endDate:(NSString *)end
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];

    
    NSDate *startDate = [dateFormatter dateFromString:start];
    NSDate *endDate = [dateFormatter dateFromString:end];
    NSTimeInterval time = [endDate timeIntervalSinceDate:startDate];
    return time;
}


例子1:限制时间范围为30天

                    NSInteger day  = [QCT_Common contrastTimeBackDayWithStartDate:weakSelf.filterViewModel.timeModel.startStr endDate:weakSelf.filterViewModel.timeModel.endStr];
                    NSLog(@"day: %ld",(long)day);
                    
                    
                    if (day > 29) {
                        [weakSelf showHUDMessage:QCTLocal(@"time_interval_should_not_exceed_30_days")];
                        return;
                    }

例子2: 数据过滤: 获取最近7天的数据

        // 数据过滤:  获取最近7天的数据
        NSMutableString *str = [[NSMutableString alloc]initWithString: [QCT_Common get4TodayTimeWithDateFormat:@"yyyy-MM-dd HH:mm:ss"]];        
        NSMutableArray *tmp = [NSMutableArray array];

        for (QCTReceiptDetailModel *obj in tmparr) {
            NSInteger day  = [QCT_Common contrastTimeBackDayWithStartDate:obj.completeTime endDate:str DateFormat:@"yyyy-MM-dd HH:mm:ss"];//  endDate 大            
            NSLog(@"day: %ld",(long)day);
            if (day > 6) {                                
            }else{
                [tmp addObject:obj];                
            }            
        }

2.3 时间格式化

blog.csdn.net/z929118967/…

see also

iOS隐私安全:用户协议及隐私政策弹框(包含超链接属性、demo支持中英文切换)https://kunnan.blog.csdn.net/article/details/103902362