利用NSCalendar类实现日期的比较

时间:2023-03-09 07:41:44
利用NSCalendar类实现日期的比较

在项目中日期的显示经常会当天的显示时分,当月的显示日时和分,以此类推,难免会涉及到日期的比较,下面介绍一下日期比较的两种方法

比较日期有两种方法

一种是通过系统的NSCalendar类实现

NSString * date = @"2016-10-12 13:12:12";
    //创建日期格式
    NSDateFormatter * dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    //字符串转为日期
    NSDate *showDate =[dateFormat dateFromString:date];
    //创建日历类
    NSCalendar * calendar = [NSCalendar currentCalendar];
    //比较现在的时间和
    NSDateComponents * components =  [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:showDate toDate:[NSDate date] options:NSCalendarWrapComponents];
    if (components.year) {
         NSLog(@"同一年");
    }else{
        if (components.month) {
            NSLog(@"同一月");
        }else{
           NSLog(@"不同月");
        }
    }

另一种方法是:

利用时间的实例方法timeIntervalSinceDate:就会得出两个时间相差的秒数,再计算相差的天数

    NSString * date = @"2016-10-13 9:04:00";
//创建日期格式
NSDateFormatter * dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
//字符串转为日期
NSDate *showDate =[dateFormat dateFromString:date]; NSDate * nowDate = [NSDate date];
NSTimeInterval timeInterval = [nowDate timeIntervalSinceDate:showDate]; NSLog(@"分差=%f",timeInterval/60.00);//分差
NSLog(@"时差=%f",timeInterval/3600.00);//时差
NSLog(@"天数差=%f",timeInterval/3600.00/);//天数差,如果是0说明是当天,否则不是当天