聊天时间戳转日期

时间戳精度为秒

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
+(NSString *)getMessageDateWithTimestamp:(int64_t)Timestamp
{

NSDate *messageDate = [NSDate dateWithTimeIntervalSince1970:Timestamp];
NSDate *date=[NSDate date];
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
NSInteger interval = [timeZone secondsFromGMTForDate:date];
date = [date dateByAddingTimeInterval:interval];
NSString* dateString=[NSString stringWithFormat:@"%@ 00:00:00",[[NSString stringWithFormat:@"%@",date] substringToIndex:10]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *zeroDate = [dateFormatter dateFromString:dateString];
zeroDate = [zeroDate dateByAddingTimeInterval:interval];
int64_t beforeLogoutTimestamp=[zeroDate timeIntervalSince1970]*1;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale systemLocale]];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
[formatter setDateFormat:@"YYYY/MM/dd HH:mm"];

if (Timestamp-beforeLogoutTimestamp > 0)
{
///今天
[formatter setDateFormat:@"HH:mm"];
return [formatter stringFromDate:messageDate];
}
else
{
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:zeroDate];
components.day -= 1;
NSDate* yestoday=[cal dateFromComponents:components];
yestoday = [yestoday dateByAddingTimeInterval:interval];

int64_t yestodayTimestamp=[yestoday timeIntervalSince1970];

if (Timestamp-yestodayTimestamp > 0)
{
///昨天
[formatter setDateFormat:@"昨天 HH:mm"];
return [formatter stringFromDate:messageDate];
}
else
{
for (int i = 1; i <= 6; i++)
{
components.day -= 1;
NSDate *nowdate = [cal dateFromComponents:components];
nowdate = [nowdate dateByAddingTimeInterval:interval];

NSDateComponents *componentsT = [cal components:NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:nowdate];

NSString* weekday;
if (componentsT.weekday==1)
{
weekday=@"星期日";
}
else if (componentsT.weekday==2)
{
weekday=@"星期一";
}
else if (componentsT.weekday==3)
{
weekday=@"星期二";
}
else if (componentsT.weekday==4)
{
weekday=@"星期三";
}
else if (componentsT.weekday==5)
{
weekday=@"星期四";
}
else if (componentsT.weekday==6)
{
weekday=@"星期五";
}
else if (componentsT.weekday==7)
{
weekday=@"星期六";
}

int64_t nowTimestamp=[nowdate timeIntervalSince1970];
if(Timestamp-nowTimestamp > 0)
{
[formatter setDateFormat:[NSString stringWithFormat:@"%@ HH:mm",weekday]];
return [formatter stringFromDate:messageDate];
}
}
[formatter setDateFormat:@"YYYY/MM/dd"];
return [formatter stringFromDate:messageDate];
}
}
}