سؤال

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?

هل كانت مفيدة؟

المحلول

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

[ components setTimeZone:[ NSTimeZone systemTimeZone ] ] ;

نصائح أخرى

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.

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).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top