ios 计算两个时间相差秒数_iOS NSDate时间换算

这篇博客介绍了如何在iOS中使用NSDate计算两个时间点之间的相差秒数。通过实例代码展示了从NSDate获取当前时间,计算两个日期之间的年、月、日、小时、分钟和秒的差值,并且获取时间戳以及计算距离当前时间的秒数。

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

// 1、获取当前时间

NSDate *now = [NSDate date];

NSDateFormatter *nowFormate = [[NSDateFormatter alloc] init];

nowFormate.dateFormat = @"yyyy-MM-dd HH:mm:ss";

NSString *nowTime = [nowFormate stringFromDate:now];

NSLog(@"nowTime = %@",nowTime);

// 2、拿现在的时间和过去时间或者将来时间对比,计算出相差多少天,多少年,多少秒等等;

NSDate *beforTime = [nowFormate dateFromString:@"2014-06-14 19:25:00"];

NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

//世纪

NSInteger era  = kCFCalendarUnitEra;

//年

NSInteger year = kCFCalendarUnitYear;

//月

NSInteger month = kCFCalendarUnitMonth;

//小时

NSInteger hour = kCFCalendarUnitHour;

//分钟

NSInteger minute = kCFCalendarUnitMinute;

//秒

NSInteger second = kCFCalendarUnitSecond;

NSDateComponents *compsEra = [calender components:era fromDate:beforTime toDate:now options:0];

NSDateComponents *compsYear = [calender components:year fromDate:beforTime toDate:now options:0];

NSDateComponents *compsMonth = [calender components:month fromDate:beforTime toDate:now options:0];

NSDateComponents *compsHour = [calender components:hour fromDate:beforTime toDate:now options:0];

NSDateComponents *compsMinute = [calender components:minute fromDate:beforTime toDate:now options:0];

NSDateComponents *compsSecond = [calender components:second fromDate:beforTime toDate:now options:0];

NSLog(@"相差世纪个数 = %ld",[compsEra era]);

NSLog(@"相差年个数 = %ld",[compsYear year]);

NSLog(@"相差月个数 = %ld",[compsMonth month]);

NSLog(@"相差小时个数 = %ld",[compsHour hour]);

NSLog(@"相差分钟个数 = %ld",[compsMinute minute]);

NSLog(@"相差秒个数 = %ld",[compsSecond second]);

// 3、获取时间戳(相对于1970年)

CGFloat timestamp = now.timeIntervalSince1970;

NSLog(@"距离1970年有多少秒 = %f",timestamp);

// 4、计算距离现在有多少秒

CGFloat sinceNow = beforTime.timeIntervalSinceNow;

NSLog(@"距离现在有多少秒 = %f",fabs(sinceNow));

}

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值