ios三種NSDate計算年月日,以及比較天數的方法

一:通過時間戳除以每天的秒數,得到當前的天數,主要用來比較天數,用來製作不帶時分秒的Date。

    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970];
    int daySeconds = 24 * 60 * 60;
    NSInteger theDays = interval / daySeconds; 
    //theDays: 16658
    NSDate *theDate = [NSDate dateWithTimeIntervalSince1970:allDays * daySeconds];
    //theDate: 2015-08-11 00:00:00 +0000

二:可以獲得當前日期的幾乎所有日期相關

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"'公元前/後:'G  '年份:'u'='yyyy'='yy '季度:'q'='qqq'='qqqq '月份:'M'='MMM'='MMMM '今天是今年第幾周:'w '今天是本月第幾周:'W  '今天是今年第幾天:'D '今天是本月第幾天:'d '星期:'c'='ccc'='cccc '上午/下午:'a '小時:'h'='H '分鐘:'m '秒:'s '毫秒:'SSS  '這一天已過多少毫秒:'A  '時區名稱:'zzzz'='vvvv '時區編號:'Z "];
NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]);

三:獲得當前日期的年,月,日,(時,分,秒)

    NSDate *currentDate = [NSDate date];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentDate];
    NSInteger m = [components month]; // month
    NSInteger d = [components day]; // day
    NSInteger y = [components year]; // year
發佈了33 篇原創文章 · 獲贊 8 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章