時間與日期詳解

時間日曆類

導語

NSDate、 NSCalendar、 NSDateComponents和 NSTimeZone類,提供了日期和時間的編程和格式支持。

NSDate: 表示一個絕對的時間戳
NSTimeZone: 時區信息
NSCalendar: 日曆類,可以計算大部分日期
NSDateFormatter: 用來在日期和字符串之間轉換

一、NSDate

1. + (instancetype)init

//以下兩行代碼的作用是相同的,默認初始化,並返回當前時間
NSDate *date1 = [[NSDate alloc] init];
NSDate *date2 = [NSDate date];

//將打印出的時間格式:2015-10-26 20:20:10 +0000

2. - (NSTimeInterval)timeIntervalSince1970

//The interval between the date object and 
//  00:00:00 UTC on 1 January 1970. (read-only)
NSDate *now = [NSDate date];
NSLog(@"%f", [now timeIntervalSince1970]);

//返回當前時間到1970年1月1日00:00:00的秒數

3. 求當前時區的當前時間

由於NSDate *date = [NSDate date];語句產生的是一個GMT時間,並不是北京時間,所以在開發時就需要對這個date進行處理,操作如下

- (NSDate *)dateNow {
    //獲取當前時區的當前時間
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    NSDate *localeDate = [date dateByAddingTimeInterval:interval];
    return localeDate;
}

二、NSCalendar

NSCalendar類能夠封裝日曆信息,調度多個時間段。該類含有多種日曆的實現代碼,其中包括公曆、中國農曆、日本歷、伊斯蘭曆等等。

1. 初始化

//返回用戶當前所選區域和語言環境所對應的日曆
NSCalendar *calendar = [NSCalendar currentCalendar];

//創建一個公曆
NSCalendar *gregorianCalendar = [[NSCalendar alloc] 
            initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

2. 利用NSCalendar的實例方法求某個月的天數

- (NSInteger)maxDayForYear:(NSInteger *)year month:(NSInteger)month {
    NSString *date = [NSString stringWithFormat:@"%04ld-%02ld-01", (long)year, month];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];

    NSDate *today = [formatter dateFromString:date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSRange days = [calendar rangeOfUnit:NSCalendarUnitDay
                                  inUnit:NSCalendarUnitMonth
                                 forDate:today];

    return days.length;
    //小單位是day,大單位是month,如果today的值是2016-02-01,  
    //那麼days的range則是1-29.
    //注意如果小單位是day,大單位是year,today的值是2016-02-01,  
    //那麼days的範圍不是1-366,而是1-31,這是day的取值範圍,只可能到31了。
}

其中的- (NSRange)rangeOfUnit:(NSCalendarUnit)smaller inUnit:(NSCalendarUnit)larger forDate:(NSDate * _Nonnull)date很關鍵。
這個方法的用處是,根據參數提供的時間點,得到一個小的單位在一個大得單位裏面的取值範圍

三、NSDateFormatter

NSDateFormatter可以對輸出的NSDate日期對象進行格式化

1. 最常用的格式化

    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:MM:ss"];

    return [formatter stringFromDate:date];
    //會按照2015-01-01 00:00:00這種格式輸出
    //return類型是一個NSString *

四、常用的時間日曆封裝類

將常用的類封裝在自己的類文件中,在下次開發時可以更方便地調用。

常用的時間日曆封裝類(開發時總結的)


參考資料:wayne23的博客

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章