一、獲取當(dāng)前時(shí)間
//獲取當(dāng)前時(shí)間
- (NSString *)currentDateStr{
NSDate *currentDate = [NSDate date];//獲取當(dāng)前時(shí)間,日期
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 創(chuàng)建一個(gè)時(shí)間格式化對(duì)象
[dateFormatter setDateFormat:@"YYYY/MM/dd hh:mm:ss SS "];//設(shè)定時(shí)間格式,這里可以設(shè)置成自己需要的格式
NSString *dateString = [dateFormatter stringFromDate:currentDate];//將時(shí)間轉(zhuǎn)化成字符串
return dateString;
}
二、獲取當(dāng)前時(shí)間戳
//獲取當(dāng)前時(shí)間戳
- (NSString *)currentTimeStr{
NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//獲取當(dāng)前時(shí)間0秒后的時(shí)間
NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精確到毫秒,不乘就是精確到秒
NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
return timeString;
}
三、時(shí)間戳轉(zhuǎn)時(shí)間
// 時(shí)間戳轉(zhuǎn)時(shí)間,時(shí)間戳為13位是精確到毫秒的,10位精確到秒
- (NSString *)getDateStringWithTimeStr:(NSString *)str{
NSTimeInterval time=[str doubleValue]/1000;//傳入的時(shí)間戳str如果是精確到毫秒的記得要/1000
NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:time];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //實(shí)例化一個(gè)NSDateFormatter對(duì)象
//設(shè)定時(shí)間格式,這里可以設(shè)置成自己需要的格式
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SS"];
NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
return currentDateStr;
}
四、字符串轉(zhuǎn)時(shí)間戳
//字符串轉(zhuǎn)時(shí)間戳 如:2017-4-10 17:15:10
- (NSString *)getTimeStrWithString:(NSString *)str{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 創(chuàng)建一個(gè)時(shí)間格式化對(duì)象
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; //設(shè)定時(shí)間的格式
NSDate *tempDate = [dateFormatter dateFromString:str];//將字符串轉(zhuǎn)換為時(shí)間對(duì)象
NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[tempDate timeIntervalSince1970]*1000];//字符串轉(zhuǎn)成時(shí)間戳,精確到毫秒*1000
return timeStr;
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。