时间戳:时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数
本文对时间戳的处理主要仿照微信聊天对时间的显示,根据时间戳判断出今天,昨天,前天,以及以往的时间.
1. iOS 获取当前时间戳的方法:
NSTimeInterval timeNow=[[NSDate date] timeIntervalSince1970];
2.由时间戳转换到标准时间格式的工具类
#import <UIKit/UIKit.h>
@interface TimeStampToString : NSObject
///由时间戳转为时间格式
+(NSString *)timeStampToString:(CGFloat)timeStamp;
@end
#import "TimeStampToString.h"
@implementation TimeStampToString
+(NSString *)timeStampToString:(CGFloat)timeStamp {
NSString *timeString = [[NSString alloc]init];
//当前时间的时间戳
NSTimeInterval timeNow=[[NSDate date] timeIntervalSince1970];
//将传来的时间戳转为标准时间格式
NSTimeInterval time = timeStamp;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *tempStr= [dateFormatter stringFromDate:date];
timeString = [NSString stringWithFormat:@"%@年%@月%@日 %@",[tempStr substringWithRange:NSMakeRange(0,4)],[tempStr substringWithRange:NSMakeRange(5,2)],[tempStr substringWithRange:NSMakeRange(8,2)],[tempStr substringWithRange:NSMakeRange(11,8)]];
//当前时间
NSDate *nowDate = [NSDate date];
NSString *nowDateStr= [dateFormatter stringFromDate:nowDate];
//时间戳判断逻辑
if ([[timeString substringWithRange:NSMakeRange(0, 4)] isEqualToString:[nowDateStr substringWithRange:NSMakeRange(0, 4)]]) {
if ([[timeString substringWithRange:NSMakeRange(5,2)] isEqualToString:[nowDateStr substringWithRange:NSMakeRange(5,2)]]) {
float daySubtract = [[nowDateStr substringWithRange:NSMakeRange(8,2)] floatValue] - [[timeString substringWithRange:NSMakeRange(8,2)] floatValue];
if (daySubtract < 3) {
if (daySubtract == 0) {
NSString *string = [NSString stringWithFormat:@"今天 %@",[timeString substringWithRange:NSMakeRange(11,6)]];
return string;
}else if (daySubtract == 1) {
NSString *string = [NSString stringWithFormat:@"昨天 %@",[timeString substringWithRange:NSMakeRange(11,6)]];
return string;
}else {
if ((timeNow - time) > 3600*24*2) {
return timeString;
}else {
NSString *string = [NSString stringWithFormat:@"前天 %@",[timeString substringWithRange:NSMakeRange(11,6)]];
return string;
}
}
}else{
return timeString;
}
}else {
return timeString;
}
}else {
return timeString;
}
}
@end