iOS:NSDate 问题
我有这段代码:
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setYear:2011];
[components setDay:1];
[components setMonth:4];
NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *firstDate = [gregorianCalendar dateFromComponents:components];
NSLog(@"date:%@", firstDate);
控制台中的结果是:
date:2011-03-31
为什么???如果我设置“setDay:1”,它将是“date:2011-04-01”,不是吗?
I have this code:
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setYear:2011];
[components setDay:1];
[components setMonth:4];
NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *firstDate = [gregorianCalendar dateFromComponents:components];
NSLog(@"date:%@", firstDate);
the result in console is:
date:2011-03-31
why???? if I set "setDay:1" it would be "date:2011-04-01", no?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为这可能是与时区相关的问题。请务必在 NSDateComponents 上设置您的时区:
I think this could be a time zone related problem. Be sure to set your time zone on NSDateComponents:
它还取决于日期格式。我的
YYYY
日期是 1 年前的,我将其更改为yyyy
(小写),然后它就被修复了。对此要小心。Also it depends on the date formatting. My dates were 1 year old for
YYYY
and I change it toyyyy
(lower case) then it was fixed. Be careful about that.尝试:
来自 NSDateComponents 文档:
Try:
From the NSDateComponents docs: