2 starwar2012 starwar2012 于 2012.11.26 09:42 提问

NSDateComponent小时不正确

搞不懂为什么我用NSDateComponent修改NSDate的小时就会出错:

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点。请高手帮忙解决一下。谢谢!

1个回答

g989_1314125
g989_1314125   2012.11.26 10:15

是时区的问题:

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

映射到你的时间设置:

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);
}
}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!