您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

NSDateFormatter 與 NSDateComponents:iPhone 時間格式全解析

編輯:iOS 開發綜合

iOS 開發中處理時間是很頻繁的需求,而「拿到一個 NSDate」和「拿到使用者想看的字串」之間,通常需要兩個角色接力:NSDateFormatter 負責格式化輸出,NSDateComponents 負責拆解與組裝日期的組成部分。

一、用 NSDateFormatter 調整時間格式

// 建立 formatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

// 設定想要的格式
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

// 取出系統當前時間並格式化
NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];

// 輸出例如:2010-10-27 10:22:13
NSLog(@"%@", currentDateStr);

// 用完記得釋放
[dateFormatter release];

格式字串的規則是:yyyy 年、MM 月、dd 日、HH 是 24 小時制、hh 是 12 小時制、mm 分、ss 秒。大小寫很容易搞混,尤其 MM(月)與 mm(分)經常被寫反。

二、NSDateComponents 是什麼

NSDateComponents 以物件化、可擴充的方式封裝日期的組成單元——小時、分鐘、秒、日、月、年等等,也能用來表示一段時間量(例如 5 小時 16 分鐘)。

它有一個重要特性:不需要填滿所有欄位。新建的物件中,未設定的部分會是 NSUndefinedDateComponent。

另一個關鍵點是:NSDateComponents 本身並沒有意義,你必須知道它是「針對哪一個日曆」來解讀的。舉例來說,若你建立一個物件並設為 2004 年 5 月 6 日,此時它的「星期幾」是未定義值,而不是星期四。要取得正確的星期,必須先建立 NSCalendar,用 dateFromComponents: 轉成 NSDate,再用 components:fromDate: 把星期幾讀回來。

可讀取的欄位

era(纪元)、year、month、day、hour、minute、second、week、weekday、weekdayOrdinal、quarter。

可設定的欄位

對應的 setter:setEra:、setYear:、setMonth:、setDay:、setHour:、setMinute:、setSecond:、setWeek:、setWeekday:、setWeekdayOrdinal:、setQuarter:。

三、實例:算出 2004 年 5 月 6 日是星期幾

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:6];
[comps setMonth:5];
[comps setYear:2004];

NSCalendar *gregorian = [[NSCalendar alloc]
                          initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];

NSDateComponents *weekdayComponents =
    [gregorian components:NSWeekdayCalendarUnit fromDate:date];
int weekday = [weekdayComponents weekday];
NSLog(@"%d", weekday);

需要更完整的說明,可查閱《Date and Time Programming Guide》中的 "Calendars, Date Components, and Calendar Units" 一章。

四、實例:計算距離某個日期還有多久

NSDate *toDate   = [[NSDate alloc] initWithString:@"2012-9-29 0:0:00 +0600"];
NSDate *startDate = [[NSDate alloc] init];

NSCalendar *chineseClendar =
    [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSUInteger unitFlags =
    NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit
    | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit;

NSDateComponents *cps = [chineseClendar components:unitFlags
                                          fromDate:startDate
                                            toDate:toDate
                                           options:0];

NSInteger diffHour = [cps hour];
NSInteger diffMin  = [cps minute];
NSInteger diffSec  = [cps second];
NSInteger diffDay  = [cps day];
NSInteger diffMon  = [cps month];
NSInteger diffYear = [cps year];

NSLog(@"From Now to %@, diff: Years: %d  Months: %d, Days: %d, "
      @"Hours: %d, Mins: %d, sec: %d",
      [toDate description], diffYear, diffMon, diffDay, diffHour, diffMin, diffSec);

[toDate release];
[startDate release];
[chineseClendar release];

這裡的關鍵是 components:fromDate:toDate:options:——傳入兩個日期,它就會回傳一段「日期差異」的 components,各欄位直接就是年、月、日、時、分、秒的差值,不必自己去除 86400 這種魔法數字。

補充一點:上面用的 initWithString: 與 descriptionWithCalendarFormat: 都屬於非公開/私有 API,上架時應避免使用。正式環境請改用 NSDateFormatter 的 dateFromString: 來解析字串。

摘自 hufeng825的專欄

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved