獲取當(dāng)前時(shí)間及時(shí)間戳的互換

在項(xiàng)目開發(fā)中,難免會(huì)遇到使用當(dāng)前時(shí)間,比如實(shí)現(xiàn)網(wǎng)絡(luò)請(qǐng)求上傳報(bào)文、預(yù)約、日歷等功能。

1. 獲取年月日時(shí)分秒

實(shí)現(xiàn)代碼:

 NSDate *date1 = [NSDate date];
 NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
 [formatter1 setDateStyle:NSDateFormatterMediumStyle];
 [formatter1 setTimeStyle:NSDateFormatterShortStyle];
 [formatter1 setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
 NSString *DateTime1 = [formatter1 stringFromDate:date1];

str就是我們需要的時(shí)間,代碼中("YYYY-MM-dd HH:mm:ss")這個(gè)時(shí)間的樣式是可以根據(jù)我們的需求進(jìn)行修改的,比如: 20170901112253 ==> ("YYYYMMddHHmmss")

如果只想獲取年月,代碼如下:

NSDate *date1 = [NSDate date];
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateStyle:NSDateFormatterMediumStyle];
[formatter1 setTimeStyle:NSDateFormatterShortStyle];
[formatter1 setDateFormat:@"YYYY-MM"];
NSString *DateTime1 = [formatter1 stringFromDate:date1];

2. 區(qū)分系統(tǒng)時(shí)間是24小時(shí)制還是12小時(shí)制

代碼如下:

//獲取系統(tǒng)是24小時(shí)制或者12小時(shí)制
NSString *formatStringForHours = [NSDateFormatter      dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
NSRange contains = [formatStringForHours rangeOfString:@"a"];
BOOL thisAMPM = contains.location != NSNotFound;
thisAMPM==TURE為12小時(shí)制,否則為24小時(shí)制

3. 字符串轉(zhuǎn)時(shí)間戳

代碼如下:

//字符串轉(zhuǎn)時(shí)間戳
//datenow為當(dāng)前時(shí)間
NSString *timeSp = [NSString stringWithFormat:@"%d", (long)    [datenow timeIntervalSince1970]];  
//時(shí)間戳的值
NSLog(@"timeSp:%@",timeSp); 

4. 時(shí)間戳轉(zhuǎn)字符串

代碼如下:

//時(shí)間戳轉(zhuǎn)字符串
NSString *timeStr = "1506064573";
NSTimeInterval interval=[timeStr doubleValue] / 1000.0;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
//實(shí)例化一個(gè)NSDateFormatter對(duì)象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
//設(shè)定時(shí)間格式,這里可以設(shè)置成自己需要的格式
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *currentDateStr = [dateFormatter stringFromDate:date]; 

希望可以幫助大家 如果哪里有什么不對(duì)或者不足的地方,還望讀者多多提意見 !

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容