标准时间即(2017-05-05 17:33:09)字符串;
//时间戳 转 标准时间(2017-07-15格式) - wsx注释
+(NSString *)timeStampSwitchStandardTime:(long long)timeStamp{
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp];//秒数@"1493976789"转时间
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSString *time = [formatter stringFromDate:date];//时间转标准时间字符串
NSLog(@"标准时间字符串:%@",time);
return time;
}
打印截图:
进阶转换,显示多少秒/分/小时/天之前,代码如下:
//时间戳 转 标准时间(2017-07-15格式) - wsx注释
+(NSString *)timeStampSwitchStandardTime:(long long)timeStamp{
NSDate *nowDate = [NSDate date];
NSDate *oldDate = [NSDate dateWithTimeIntervalSince1970:timeStamp];//时间戳转Date时间
// 两个时间戳的间隔 返回的是秒
NSTimeInterval timeInterval = [nowDate timeIntervalSinceDate:oldDate];
NSInteger interval = (NSInteger)timeInterval;
//日期获取 - wsx注释
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd"];
NSString *time;
if (interval < 60 ) {
time = [NSString stringWithFormat:@"%ld秒前",(long)interval];
}else if (interval < 60*60){
time = [NSString stringWithFormat:@"%ld分前",(long)interval/60];
}else if (interval < 60*60*24){
time = [NSString stringWithFormat:@"%ld小时前",(long)interval/3600];
}else if (interval < 60*60*24*2){
time = @"昨天";
}else if (interval < 60*60*24*3){
time = @"前天";
}else{
time = [formatter stringFromDate:oldDate];//时间转标准时间字符串
}
NSLog(@"标准时间字符串:%@",time);
return time;
}
标准时间转时间戳:
- (NSString *)obtainTimeStampFromStandardTimeWithStartTime:(NSString *)startTime EndTime:(NSString *)endTime {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // hh表示:12小时制,HH表示:24小时制
//设置时区,这个对于时间的处理很重要
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
[dateFormatter setTimeZone:timeZone];
NSString *nowTimeStamp = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
// 开始时间转换
NSDate *startDate = [dateFormatter dateFromString:startTime]; // 将standardTime字符串按dateFormatter转成NSDate
NSString *startTimeStamp = [NSString stringWithFormat:@"%ld", (long)[startDate timeIntervalSince1970]]; // date与当前时间差8小时 // 得到秒
// 结束时间转换
NSDate *endDate = [dateFormatter dateFromString:endTime];
NSString *endTimeStamp = [NSString stringWithFormat:@"%ld", (long)[endDate timeIntervalSince1970]]; // 得到秒
// 比较时间差
if ([[NSDate date] timeIntervalSinceDate:startDate] < 0.0f) {
return @"未开始";
} else if ([[NSDate date] timeIntervalSinceDate:endDate] > 0.0f) {
return @"已结束";
}
return @"进行中";
}