IOS: problem with NSDate

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

result in console:

date:2011-03-31

why???? if I set "setDay: 1", it will be "date: 2011-04-01", no?

+4
source share
3 answers

I think this may be a timezone issue. Remember to set the time zone to NSDateComponents:

[ components setTimeZone:[ NSTimeZone systemTimeZone ] ] ;
+2
source

It also depends on the formatting of the date. My dates were 1 year for YYYYand I change it to YYYY(lower case), after which it has been fixed. Be careful.

+1
source

Try:

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

NSDateComponents:

NSDateComponents , NSCalendar dateFromComponents: . , ( ). , , 0 1, , . , ( ).

0

All Articles