NSDate和NSCalendar

  • 创建时间对象,以当前时间为标准
//1.创建时间对象,以当前时间为标准
NSDate *now = [NSDate date];
  • 在该时间基础上加上10s
//2.在该时间基础上加上10s
now = [now dateByAddingTimeInterval:10];
  • 获取当前时区
//3.获取当前时区
NSTimeZone *zone = [NSTimeZone systemTimeZone];
  • 获取当前时区和东八区的时间差
//4.获取当前时区和东八区的时间差
NSInteger seconds = [zone secondsFromGMTForDate:now];
NSLog(@"%li",(long)seconds);
NSDate *newnow = [now dateByAddingTimeInterval:seconds];
NSLog(@"zone = %@", zone);
NSLog(@"newnow = %@", newnow);
  • 时间格式化
//5.时间格式化
//创建一个时间格式化对象
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//给时间格式化对象格式化
formatter.dateFormat = @"yyyy年MM月dd日 HH时mm分ss秒";
NSString *res = [formatter stringFromDate:now];
NSLog(@"%@", res);
  • NSString -> NSDate
//6.NSString -> NSDate
NSString *str = @"2018年02月17日 15时13分55秒";
NSDateFormatter *newformatter = [[NSDateFormatter alloc] init];
newformatter.dateFormat = @"yyyy年MM月dd日 HH时mm分ss秒";
NSDate *newDate = [newformatter dateFromString:str];
NSLog(@"%@", newDate);

从所给的时间里面或获取元素
NSDate *now = [[NSDate alloc] init];
//日历对象
NSCalendar *calendar = [NSCalendar currentCalendar];
//从提供的时间中获取年份
NSDateComponents *cmps = [calendar components:NSCalendarUnitYear fromDate:now];
NSCalendarUnit枚举
NSDate *now = [[NSDate alloc] init];
//日历对象
//通过 | 可以连接多个枚举
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
//从提供的时间中获取年份
NSDateComponents *cmps = [calendar components:type fromDate:now];
NSLog(@"%ld", cmps.year);
NSLog(@"%ld", cmps.month);
NSLog(@"%ld", cmps.day);
NSLog(@"%ld", cmps.hour);
NSLog(@"%ld", cmps.minute);
NSLog(@"%ld", cmps.second);
比较两个时间的差值
//其中一个比较时间
NSString *str = @"2018年02月17日 15时13分55秒";
NSDateFormatter *newformatter = [[NSDateFormatter alloc] init];
newformatter.dateFormat = @"yyyy年MM月dd日 HH时mm分ss秒";
NSDate *newDate = [newformatter dateFromString:str];
//另一个比较时间
NSDate *now = [NSDate date];
//日历对象
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
//比较方法,
NSDateComponents *res= [calendar components:type fromDate:newDate toDate:now options:0];
NSLog(@"%@", res);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值