zoukankan      html  css  js  c++  java
  • 利用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/24);//天数差,如果是0说明是当天,否则不是当天
  • 相关阅读:
    bzoj4152 [AMPPZ2014]The Captain
    bzoj2429 [HAOI2006]聪明的猴子
    bzoj1196 [HNOI2006]公路修建问题
    bzoj1083 [SCOI2005]繁忙的都市
    bzoj1050 [HAOI2006]旅行comf
    bzoj1088 [SCOI2005]扫雷Mine
    bzoj1085 [SCOI2005]骑士精神
    bzoj3437 小P的牧场
    bzoj1296 [SCOI2009]粉刷匠
    A1046 Shortest Distance (20)(20 分)
  • 原文地址:https://www.cnblogs.com/liyy2015/p/5957377.html
Copyright © 2011-2022 走看看