从NSDateComponents创建NSDate一天 [英] Creating NSDate from NSDateComponents off by one day
问题描述
我正在尝试设置单元测试的特定日期:
I'm trying to set a particular date for a unit test:
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];
NSDate *date = [calendar dateFromComponents:components];
NSLog(@"Date I tried to set: %@", date);
然而,这打印出我尝试设置的日期:2011-05-11 17:00: 00 +0000。这个日期似乎有一天了,我不知道为什么打印时间为17:00:00。
为什么会这样?
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没有与之关联的任何时区数据。实际上距离格林威治标准时间2001年1月1日的第一个瞬间只有几秒钟。因此,日期组件和日历使用您的本地时区创建NSDate。 NSDate是格林尼治标准时间1/1/2001 00:00的正确秒数,但是当您记录它时,它会以GMT而不是本地时区显示日期。如果您将记录的时间调整为您的时区,则为2011-05-12 01:00:00。
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.
这篇关于从NSDateComponents创建NSDate一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!