从 NSDateComponents 创建 NSDate 缩短了一天
我正在尝试为单元测试设置特定日期:
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。 这是为什么呢?
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);
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSDate 没有任何与之关联的时区数据。实际上距离“2001 年 1 月 1 日格林威治标准时间第一时刻”仅几秒。因此,日期组件和日历正在使用您当地的时区创建 NSDate。该 NSDate 是从 1/1/2001 00:00 GMT 开始的正确秒数,但是当您记录它时,它会显示 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.
尝试一下
或者也许你想要
Try
or maybe you want