为什么我输出错误的时间与正确的时区?

时间:2013-01-12 17:50:00

标签: ios objective-c xcode timezone output

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

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

2 个答案:

答案 0 :(得分:7)

你正在把年,月,日组成部分搞定。

执行:

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

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

旁注:由于NSCalendarUnitNSUInteger的位域类型,我传入NSUIntegerMax以检索所有可能的日历单位。这样我就不必进行大规模的OR语句。

答案 1 :(得分:4)

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

来自Apple文档:

  

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

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

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

相关问题