iOS:NSDate 问题

发布于 2024-11-04 18:44:15 字数 525 浏览 0 评论 0原文

我有这段代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

×眷恋的温暖 2024-11-11 18:44:15

我认为这可能是与时区相关的问题。请务必在 NSDateComponents 上设置您的时区:

[ components setTimeZone:[ NSTimeZone systemTimeZone ] ] ;

I think this could be a time zone related problem. Be sure to set your time zone on NSDateComponents:

[ components setTimeZone:[ NSTimeZone systemTimeZone ] ] ;
会傲 2024-11-11 18:44:15

它还取决于日期格式。我的 YYYY 日期是 1 年前的,我将其更改为 yyyy (小写),然后它就被修复了。对此要小心。

Also it depends on the date formatting. My dates were 1 year old for YYYY and I change it to yyyy (lower case) then it was fixed. Be careful about that.

誰認得朕 2024-11-11 18:44:15

尝试:

   [components setWeekdayOrdinal:1]; // The first day in the month

来自 NSDateComponents 文档:

您可以配置 NSDateComponents 的实例来指定日期的组成部分,然后使用 NSCalendar 方法 dateFromComponents: 创建相应的日期对象。您可以根据需要(或选择)提供任意数量的组件。当计算绝对时间的信息不完整时,日历通常会选择默认值(例如 0 和 1),但这是特定于日历的选择。如果您提供的信息不一致,则会执行特定于日历的消歧操作(这可能涉及忽略一个或多个参数)。

Try:

   [components setWeekdayOrdinal:1]; // The first day in the month

From the NSDateComponents docs:

You can configure an instance of NSDateComponents to specify the components of a date and then use the NSCalendar method dateFromComponents: to create the corresponding date object. You can provide as many components as you need (or choose to). When there is incomplete information to compute an absolute time, default values such as 0 and 1 are usually chosen by a calendar, but this is a calendar-specific choice. If you provide inconsistent information, calendar-specific disambiguation is performed (which may involve ignoring one or more of the parameters).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文