4

为什么我得到这个输出时间:

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

4

2 回答 2

7

您缺少年、月和日组件。

做:

NSDateComponents *components = [calendar components:NSUIntegerMax fromDate:[NSDate date]];

现在这应该给你正确的日期。

旁注:由于NSCalendarUnit是 的位域类型定义NSUInteger,我传入NSUIntegerMax以检索所有可能的日历单位。这样我就不必有大量的按位 OR 语句。

于 2013-01-12T17:56:25.760 回答
4

您还需要使用该calendar components:方法请求年、月和日。

来自苹果文档:

NSDateComponents 的实例不负责回答有关超出其初始化信息的日期的问题。

NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit fromDate:[NSDate date]];

日期的 NSLog 将使用默认时区显示时间。

于 2013-01-12T17:58:32.607 回答