在項(xiàng)目開(kāi)發(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];