开发中经常用到时间戳,*、/ 1000是秒和毫秒的换算。
1.当前时间
long long 类型时间戳: NSTimeInterval time=([[NSDate date] timeIntervalSince1970])*1000;
long long t = (long long)time;
String类型当前时间:NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";//格式自定义
NSString *str = [formatter stringFromDate:[NSDate date]];
2.获取今日零点时间
(1)时间戳:
- (long long) todayStartTime {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
NSDate *startDate = [calendar dateFromComponents:components];
return (long long)[startDate timeIntervalSince1970]*1000 ;
}
(2)String日期:
- (NSString) todayStartTime {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
NSDate *startDate = [calendar dateFromComponents:components];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy:MM:dd:HH:mm:ss"];
return [dateFormatter stringFromDate:startDate];
}
3.时间戳和时间转换
我们需要显示日期,服务器给我们的是时间戳参考(1),给我们的是系统时间格式的字符串参考(2)、(3)
(1)时间戳转换成日期:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
//self.nowTime是13位时间戳,把时间戳先转换为NSDate,再转换为String展示
NSDate* date = [NSDate dateWithTimeIntervalSince1970:(double)self.nowTime/1000];
NSString *riQi = [formatter stringFromDate:date];
(2)String日期转换成long long时间戳:
//例如日期为string类型 model.createTime =@"Aug 1, 2017 10:53:20 AM"
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"MMM d, yyyy h:mm:ss a";
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSDate* date = [formatter dateFromString:model.createTime];
NSTimeInterval time=([date timeIntervalSince1970])*1000;
long long t = (long long)time;
(3)将String类型日期变换格式依旧以String日期显示:
依旧以(2)中为例,只是在最后不转时间戳,将NSDate 转为要显示的日期
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"MMM d, yyyy h:mm:ss a";
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSDate* date = [formatter dateFromString:model.createTime];
formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
NSString *riQi = [formatter stringFromDate:date];
4.时间差展示
(1)展示模糊的时间 过去时间戳距离当前时间的时差 timeInterval 为秒级,毫秒级的自行/1000
//timeInterval过去的时间戳
+ (NSString *)getFriendlyDateString:(NSTimeInterval)timeInterval
{
NSDate *theDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
//算出时间戳的差值
NSTimeInterval diff = -theDate.timeIntervalSinceNow;
NSInteger minute = 60 ;// 1分钟
NSInteger hour = 60 * minute;// 1小时
NSInteger day = 24 * hour;// 1天
NSInteger month = 31 * day;// 月
NSInteger year = 12 * month;// 年
long r = 0;
if (diff > year) {
r = (diff / year);
return [NSString stringWithFormat:@"%ld年前",r];
}
if (diff > month) {
r = (diff / month);
return [NSString stringWithFormat:@"%ld个月前",r];
}
if (diff > day) {
r = (diff / day);
return [NSString stringWithFormat:@"%ld天前",r];
}
if (diff > hour) {
r = (diff / hour);
return [NSString stringWithFormat:@"%ld个小时前",r];
}
if (diff > minute) {
r = (diff / minute);
return [NSString stringWithFormat:@"%ld分钟前",r];
}
return @"刚刚";
}
(2)精确时间展示 秒级时间段时间戳转化为String
+(NSString*)getDetailYuTimeWith:(NSInteger)peroidTime{
NSInteger minute = 60 ;// 1分钟
NSInteger hour = 60 * minute;// 1小时
NSInteger day = 24 * hour;// 1天
NSInteger month = 31 * day;// 月
NSInteger year = 12 * month;// 年
//时间数
NSInteger nian = peroidTime/year;//有几年
NSInteger yue = (peroidTime-nian*year)/month;//有几月
NSInteger ri = (peroidTime-nian*year-yue*month)/day;//有几日
NSInteger shi = (peroidTime-nian*year-yue*month-ri*day)/hour;//有几时
NSInteger fen = (peroidTime-nian*year-yue*month-ri*day-shi*hour)/minute;//有几分
NSInteger miao = peroidTime-nian*year-yue*month-ri*day-shi*hour-fen*minute;//有几秒
if (nian!=0) {
return [NSString stringWithFormat:@"%zd年%02zd月%02zd天%02zd小时%02zd分%02zd秒",nian,yue,ri,shi,fen,miao];
}else if (yue!=0){
return [NSString stringWithFormat:@"%02zd月%02zd天%02zd小时%02zd分%02zd秒",yue,ri,shi,fen,miao];
}else if (ri != 0){
return [NSString stringWithFormat:@"%02zd天%02zd小时%02zd分%02zd秒",ri,shi,fen,miao];
}else if (shi!=0){
return [NSString stringWithFormat:@"%02zd小时%02zd分%02zd秒",shi,fen,miao];
}else if (fen!=0){
return [NSString stringWithFormat:@"%02zd分%02zd秒",fen,miao];
}else{
return [NSString stringWithFormat:@"%02zd秒",miao];
}
}
以上关于时间的转换或封装,是个人经验,如有高手请指点,分享出来,希望大家可以在写代码的时候节约时间,不会把时间浪费在时间戳的问题上,有些时候时间戳的问题很折磨人,会浪费很多不必要的时间,比如去年的时候,因为sqlite3存储毫秒级时间戳崩溃,百思不得其解,最后发现13位的存储sq语句中字段应该用bigint类型才可以。
关于第4点,有个瑕疵就是时间段超过月会不精确,目前按30或31天粗略估算的,这个问题我想到了更好的方式解决,通过日历对比,如下
//定义格式化对象
let sharedDateFormater = DateFormatter()
var created_at:String?
//get 计算型属性
var timeText: String? {
//1.实例化日期格式化对象
//2.指定格式化符
sharedDateFormater.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
//在真机上必须设置本地化信息否则转换失败
sharedDateFormater.locale = Locale(identifier: "en")
//3.将字符串转换日期对象
guard let sinaDate = sharedDateFormater.date(from: self.created_at ?? "") else {
return "穿越时空的少年"
}
//print(sinaDate)
//4.处理日期
//4.1 判断是否是今年 Calendar 提供非常丰富的日期处理函数
let calender = Calendar.current
let currentDate = Date()
let result = calender.dateComponents([.day,.year], from: sinaDate, to: currentDate)
if result.year == 0 {
//今年
if calender.isDateInToday(sinaDate) {
//今天
//获取当前时间和sinaDate秒的差值
let delta = currentDate.timeIntervalSince(sinaDate)
if delta < 60 {
//刚刚
return "刚刚"
} else if delta < 3600 {
return "\(Int(delta / 60))分钟前"
} else {
return "\(Int(delta / 3600))小时前"
}
} else if calender.isDateInYesterday(sinaDate) {
//昨天 昨天 HH:mm
sharedDateFormater.dateFormat = "昨天 HH:mm"
return sharedDateFormater.string(from: sinaDate)
} else {
//其他 MM-dd HH:mm
sharedDateFormater.dateFormat = "MM-dd HH:mm"
return sharedDateFormater.string(from: sinaDate)
}
} else {
//非当年
sharedDateFormater.dateFormat = "yyyy-MM-dd HH:mm"
return sharedDateFormater.string(from: sinaDate)
}
}
另外时间差如果不超过24小时,可以用下面这个,例如
// 时间戳的差转换成时间显示去掉时区8小时
NSTimeInterval response = 3684;
NSDate *date = [[NSDate alloc]initWithTimeIntervalSince1970:response-28800];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSString * responseTime = [dateFormatter stringFromDate:date];
NSLog(@"=%@",responseTime);
结果为=01:01:24