利用NSCalendar類實現日期的比較,nscalendar日期

來源:互聯網
上載者:User

利用NSCalendar類實現日期的比較,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說明是當天,否則不是當天

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.