4

我有这个代码:

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”,它将是“日期:2011-04-01”,不是吗?

4

3 回答 3

2

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

[ components setTimeZone:[ NSTimeZone systemTimeZone ] ] ;
于 2011-05-04T17:23:46.877 回答
1

这也取决于日期格式。我的日期是 1 岁YYYY,我将其更改为yyyy(小写)然后它被修复了。小心点。

于 2012-10-20T18:29:28.653 回答
0

尝试:

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

从 NSDateComponents 文档:

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

于 2011-05-04T17:52:33.793 回答