iOS 计算时间戳之间的时间差

NSString *beginTimestamp = @"1498790372";
NSString *endTimestamp = @"1500134340"; 
    
NSTimeInterval timer1 = [beginTimestamp doubleValue];
NSTimeInterval timer2 = [endTimestamp doubleValue];
    
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
NSDate* date = [NSDate dateWithTimeIntervalSince1970:timer1];
NSString *dateString1 = [formatter stringFromDate:date];
    
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:timer2];
NSString *dateString2 = [formatter stringFromDate:date2];
    
// 日历对象(方便比较两个日期之间的差距)
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit =NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *cmps = [calendar components:unit fromDate:date toDate:date2 options:0];

NSLog(@"%@",dateString1);
NSLog(@"%@",dateString2);
// 获得某个时间的年月日时分秒
NSLog(@"差值%ld天,%ld小时%ld分%ld秒",cmps.day ,cmps.hour, cmps.minute,cmps.second);
输出结果:
2017-06-30 10:39:32
2017-07-15 23:59:00
差值15天,13小时19分28秒

你可能感兴趣的:(iOS 计算时间戳之间的时间差)