开发者

Creating NSDate from NSDateComponents off by one day

I'm trying to set a particular date for a unit test:

NSCalendar *calendar = [[NSCalend开发者_如何学运维ar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setCalendar:calendar];
[components setYear:2011];
[components setMonth:5];
[components setDay:12];
[components setHour:1];
[components setMinute:0];
[components setSecond:0];

NSDate *date = [calendar dateFromComponents:components];
NSLog(@"Date I tried to set: %@", date);

However, this prints out "Date I tried to set: 2011-05-11 17:00:00 +0000." The date seems off by one day, and I have no idea why it's printing out the time as 17:00:00. Why is this?


NSDate doesn't have any timezone data associated with it. It is actually just a number of seconds from "the first instant of 1 January 2001, GMT." So the date components and calendar are creating an NSDate using your local timezone. That NSDate is the correct number of seconds from 1/1/2001 00:00 GMT, but when you log it, it's showing you the date in GMT instead of the local timezone. If you adjust that logged time to your timezone, it will be 2011-05-12 01:00:00.


Try

NSCalendar *calendar = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setCalendar:calendar];
[components setYear:2011];
[components setMonth:5];
[components setDay:12];
[components setHour:1];
[components setMinute:0];
[components setSecond:0];
[components setTimeZone:[NSTimeZone defaultTimeZone]];
NSDate *date = [calendar dateFromComponents:components];

or maybe you want

 [components setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜