NSDate是獲取當前時間信息的操作,代碼如下:
//初始化NSDate
NSDate *date = [NSDate date];
// 打印結果: 當前時間 date = 2017-01-13 06:50:49 +0000
NSLog(@"當前時間 date = %@",date);
可是目前具體時間是
這中間相差了8個小時的時間,這是因為時區的問題。解決方法是在后面再添上這么一段代碼:
NSTimeZone *zone = [NSTimeZone systemTimeZone];//系統所在時區
NSInteger interval = [zone secondsFromGMTForDate: date];
NSDate *localDate = [date dateByAddingTimeInterval: interval];
// 打印結果 正確當前時間 localDate = 2017-01-13 14:57:04 +0000
NSLog(@"正確當前時間 localDate = %@",localDate);
這樣就能拿到你所在時區的準=準確時間了。
但如果我們不喜歡2017-01-13 14:57:04 +0000這樣的格式,想把它轉變成另外一種表現的格式時,就要用到NSDateFormatter語句了。****NSDateFormatter****是NSDate的格式轉換語句,裝換方式為(接著上面的代碼):
NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
fmt.dateStyle = kCFDateFormatterShortStyle;
fmt.timeStyle = kCFDateFormatterShortStyle;
fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSString* dateString = [fmt stringFromDate:localDate];
NSLog(@"%@", dateString);
得到的結果為:1/13/17, 11:13 PM。
除此之外,還有其他的一些格式,在NSDateFormatterStyle里:
typedef enum {
NSDateFormatterNoStyle = kCFDateFormatterNoStyle,
NSDateFormatterShortStyle = kCFDateFormatterShortStyle,//“01/13/37” or “14:57pm”
NSDateFormatterMediumStyle = kCFDateFormatterMediumStyle,//"Nov 13, 2017"
NSDateFormatterLongStyle = kCFDateFormatterLongStyle,//"November 13, 2017” or “14:57:32pm"
NSDateFormatterFullStyle = kCFDateFormatterFullStyle//“Tuesday, April 13, 2017 AD” or “14:57:42pm PST”
} NSDateFormatterStyle;
如果我們想轉換得到中文的格式,就把上面的一段代碼
fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];//en_US指的是英語
把這段代碼改寫成:
fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];//zh_CN指的是中文
于是顯示的時間格式就會變成
typedef CF_ENUM(CFIndex, CFDateFormatterStyle) { // date and time format styles
kCFDateFormatterNoStyle = 0, // 無輸出
kCFDateFormatterShortStyle = 1, // 17-01-13 下午2:57
kCFDateFormatterMediumStyle = 2, // 2017-01-13 下午2:57:43
kCFDateFormatterLongStyle = 3, // 2017年01月13日 GMT+0800下午14時57分08秒
kCFDateFormatterFullStyle = 4 // 2017年01月13日星期五 中國標準時間下午14時57分49秒
};
我們還可以通過-setDateFormatter語句來自定義格式
NSDate *date = [NSDate date];
NSDateFormatter *f = [NSDateFormatter new];
NSString *ft = @"Y-MM-dd HH:m:SS z";
//[f setDateStyle:NSDateFormatterFullStyle];
[f setDateFormat:ft];
NSLog(@"%@",[f stringFromDate:date]);
結果為:2017-01-13 15:33:61 GMT+8
其它一些自定義格式的書寫形式:
自定義格式