ios – 为什么我输出错误的时间与正确的时区?
为什么我得到这个输出时间:
2013-01-12 18:24:37.783代码测试[10328:c07] 0001-01-01 17:12:52 0000 当我运行此代码时: NSCalendar *calendar = [NSCalendar currentCalendar]; calendar.timeZone = [NSTimeZone localTimeZone]; NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:[NSDate date]]; components.hour = 17; components.minute = 47; components.second = 0; NSDate *fire = [calendar dateFromComponents:components]; NSLog(@"%@",fire); 我尝试过默认时区,系统时区.它总是给我一个不同的分钟和秒的输出!加错了日期0001-01-01 !!!!知道为什么吗? 附加测试: 运行此代码时: NSCalendar *calendar = [NSCalendar currentCalendar]; calendar.timeZone = [NSTimeZone localTimeZone]; NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:[NSDate date]]; components.hour = (components.hour + 1) % 24; components.minute = 0; components.second = 0; NSDate *fire = [calendar dateFromComponents:components]; NSLog(@"%@",fire); 它给了我这个输出: 2013-01-12 18:41:41.552代码测试[10648:c07] 0001-01-01 18:25:52 0000 2013-01-12 18:42:16.274代码测试[10648:c07] 0001-01-01 18:25:52 0000 2013-01-12 18:42:30.310代码测试[10648:c07] 0001-01-01 18:25:52 0000 解决方法
你正在调整年,月,日组件.
做: NSDateComponents * components = [calendar components:NSUIntegerMax fromDate:[NSDate date]]; 现在,这应该给你正确的日期. 旁注:由于NSCalendarUnit是NSUInteger的bitfield typedef,我传入NSUIntegerMax来检索所有可能的日历单元.这样我就不必有大量的按位OR语句. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |