NSDate和NSCalendar的简单应用

  1. NSDate:用于创建时间对象

  2. NSTimeZone :用于创建时区对象

  3. NSDateFormatter:用于创建时间格式化对象

  4. NSCalendar:用于创建日历类

    //只要是通过date方法创建的时间对象, 对象中就保存了当前的时间
    NSDate *now = [NSDate date];
    NSLog(@"%@",now);

    //在now的基础上追加10秒
    NSDate *now1 = [now dateByAddingTimeInterval:10];
    NSLog(@"%@",now1);

    //获取当前系统的所在时区
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    NSLog(@"timeZone = %@",timeZone);

    //获取当前时区和指定时区的时间差
    NSInteger seconds =[timeZone secondsFromGMTForDate:now];
    NSLog(@"seconds = %ld",seconds);

    //创建一个时间格式化对象
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd  hh-mm-ss Z";
    //把String -> date
    NSString *now1 = @"2016-07-14 03:16:28 +0011";
    NSLog(@"%@",[formatter dateFromString:now1]);

———————————————————

    //创建一个时间对象
    NSDate *now = [NSDate date];
    //创建一个日历对象
    NSCalendar *calender = [NSCalendar currentCalendar];
    // 利用日历类从当前时间对象中获取 年月日时分秒(单独获取出来)
    // components: 参数的含义是, 问你需要获取什么?
    // 一般情况下如果一个方法接收一个参数, 这个参数是是一个枚举 , 那么可以通过|符号, 连接多个枚举值
    NSCalendarUnit type = NSCalendarUnitYear    |
                          NSCalendarUnitMonth   |
                          NSCalendarUnitDay     |
                          NSCalendarUnitHour    |
                          NSCalendarUnitMinute  |
                          NSCalendarUnitSecond;
    NSDateComponents *cmps = [calender components:type fromDate:now];
    NSLog(@"year = %ld", cmps.year);
    NSLog(@"month = %ld", cmps.month);
    NSLog(@"day = %ld", cmps.day);
    NSLog(@"hour = %ld", cmps.hour);
    NSLog(@"minute = %ld", cmps.minute);
    NSLog(@"second = %ld", cmps.second);

    //两个时间的比较
    NSString *str = @"2015-06-29 07:05:26 +0000";
    NSDateFormatter *formatter = [NSDateFormatter new];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";
    //创建一个过去的时间
    NSDate *date = [formatter dateFromString:str];
    //获取现在时间
    NSDate *now1 = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *component1 = [calendar components:type fromDate:date toDate:now1 options:0];
    NSLog(@"%ld年%ld月%ld日%ld小时%ld分钟%ld秒钟", component1.year, component1.month, component1.day, component1.hour, component1.minute, component1.second);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值