首页 > 代码库 > 时间与时间戳的转换

时间与时间戳的转换

?
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
时间戳<span>是一种时间表示方式,定义为从</span><a href=http://www.mamicode.com/"http://baike.baidu.com/view/856.htm" target="_blank">格林威治时间</a><span>1970年01月01日00时00分00秒起至现在的总秒数</span><br>//现在时间
    NSDate *nowTime = [NSDate date];
    //获取时区
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interVal = [zone secondsFromGMTForDate:nowTime];
    NSDate *localTime = [nowTime dateByAddingTimeInterval:interVal];//本地时间
    //时间戳转为时间
    NSString *time = @"1400386922";
    NSInteger dTime = [time integerValue];
    NSDate *publishTime = [NSDate dateWithTimeIntervalSince1970:dTime];
    NSLog(@"%@", publishTime);
     
    //计算时间间隔(localTime - publishTime)
    NSTimeInterval timeInterval = [localTime timeIntervalSinceDate:publishTime];
    NSLog(@"%f", timeInterval);
    if (timeInterval < 60) {
        
        NSString *time = @"刚刚";
         NSLog(@"刚刚!!");
    }
    if (timeInterval >= 60 && timeInterval < 3600) {
        int a = timeInterval / 60;
        NSString *time = [NSString stringWithFormat:@"%d分钟前", a];
        NSLog(@"%@", time);
    }
    if (timeInterval >= 3600 && timeInterval < 3600 * 24) {
        int a = timeInterval / 3600;
        
        NSString *time = [NSString stringWithFormat:@"%d小时前", a];
        NSLog(@"%@", time);
    }
    if (timeInterval >= 3600 * 24 && timeInterval < 3600 * 24 * 31) {
        int a = timeInterval / (3600 * 24);
        NSString *time = [NSString stringWithFormat:@"%d天前", a];
       NSLog(@"%@", time);
    }