天天看點

iOS關于NSDate、NSString、NSDateFormatter設定時間格式等問題

1 擷取目前時間

// 目前時間
NSDate *now = [NSDate date];
// 擷取時間中的詳細資訊年、月、日、時、分、秒
NSCalendar *calendar = [NSCalendarcurrentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit | NSHourCalendarUnit|NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *dateComponent = [calendarcomponents:unitFlags fromDate:now];
int year = [dateComponentyear];
int month = [dateComponentmonth];
int day = [dateComponentday];
int hour = [dateComponenthour];
int minute = [dateComponentminute];
int second = [dateComponentsecond];
           

2 字元串、時間互相轉換

//字元串轉換為日期
//執行個體化一個NSDateFormatter對象
NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
//設定時間格式,這裡可以設定成自己需要的格式
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date =[dateFormat dateFromString:@"1980-01-01 00:00:01"];

//日期轉換為字元串
//執行個體化一個NSDateFormatter對象
NSDateFormatter* dateFormat = [[NSDateFormatteralloc] init];
//設定時間格式,這裡可以設定成自己需要的格式
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
           

3 時間設定 dateFormat 格式注意事項

① 年 設定格式為 yyyy, 蘋果開發文檔中明确指出

It uses yyyy to specify the year component. A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), usedin the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.

年份如果用大Y會是這周的年份,小y才是标準的年份例如2013年12月29号開始,如果用大Y的話就是2014年的第一周了,年份會轉成2014

雖然不一定會出錯,但是為了安全,還是使用yyyy 比較可靠。

② iOS-NSDateFormatter 格式說明:

G: 公元時代,例如AD公元

yy: 年的後2位

yyyy: 完整年

MM: 月,顯示為1-12

MMM: 月,顯示為英文月份簡寫,如 Jan

MMMM: 月,顯示為英文月份全稱,如 Janualy

dd: 日,2位數表示,如02

d: 日,1-2位顯示,如2

EEE: 簡寫星期幾,如Sun

EEEE: 全寫星期幾,如Sunday

aa: 上下午,AM/PM

H: 時,24小時制,0-23

K:時,12小時制,0-11

m: 分,1-2位

mm: 分,2位

s: 秒,1-2位

ss: 秒,2位

S: 毫秒

常用日期結構:

yyyy-MM-dd HH:mm:ss.SSS

yyyy-MM-dd HH:mm:ss

yyyy-MM-dd

MM dd yyyy