獲取當前時間
- (NSString *)currentDateStr{
NSDate *currentDate = [NSDate date];//獲取當前時間,日期
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 創(chuàng)建一個時間格式化對象
[dateFormatter setDateFormat:@"YYYY/MM/dd hh:mm:ss SS "];//設(shè)定時間格式,這里可以設(shè)置成自己需要的格式
NSString *dateString = [dateFormatter stringFromDate:currentDate];//將時間轉(zhuǎn)化成字符串
return dateString;
}
獲取當前時間戳
- (NSString *)currentTimeStr{
NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//獲取當前時間0秒后的時間
NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精確到毫秒,不乘就是精確到秒
NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
return timeString;
}
時間戳轉(zhuǎn)時間,時間戳為13位是精確到毫秒的,10位精確到秒
- (NSString *)getDateStringWithTimeStr:(NSString *)str{
NSTimeInterval time=[str doubleValue]/1000;//傳入的時間戳str如果是精確到毫秒的記得要/1000
NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:time];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //實例化一個NSDateFormatter對象
//設(shè)定時間格式,這里可以設(shè)置成自己需要的格式
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SS"];
NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
return currentDateStr;
}
字符串轉(zhuǎn)時間戳
- (NSString *)getTimeStrWithString:(NSString *)str{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 創(chuàng)建一個時間格式化對象
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; //設(shè)定時間的格式
NSDate *tempDate = [dateFormatter dateFromString:str];//將字符串轉(zhuǎn)換為時間對象
NSString *timeStr = [NSString stringWithFormat:@"%ld", (long) [tempDate timeIntervalSince1970]*1000];//字符串轉(zhuǎn)成時間戳,精確到毫秒*1000
return timeStr;
}