NSDateComponents不会正确更改小时组件

时间:2012-11-25 22:25:56

标签: iphone ios nsdate nsdatecomponents

我无法理解为什么我无法正确更改NSDate的小时,使用NSDateComponents,我会这样做:

NSDateComponent components = [calendar components:  (NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) fromDate:today];

[components setMinute:myMinute];
[components setHour:7];

NSDate *myNewDate = [calendar dateFromComponents:components];
NSLog(@"%@",myNewDate);

但NSLog是这样的:

2012-12-08 06:00:00 +0000

有一个小时的差异,我已经设定了7但是有6个人可以帮助我吗?

1 个答案:

答案 0 :(得分:6)

它的时区 - NSDate使用GMT时间打印,因为它没有时区概念

使用

[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

使组件GMT并反映您的时间设置


工作示例

int main(int argc, char *argv[]) {
@autoreleasepool {
    NSDate *today = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:  (NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) fromDate:today];

    [components setMinute:50];
    [components setHour:7];
    [components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

    NSDate *myNewDate = [calendar dateFromComponents:components];
    NSLog(@"%@",myNewDate);
}
}