cyclingIsBetter
cyclingIsBetter

Reputation: 17591

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

the result in console is:

date:2011-03-31

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

Upvotes: 4

Views: 1024

Answers (3)

Dogan Coruh
Dogan Coruh

Reputation: 11

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.

Upvotes: 1

Rayfleck
Rayfleck

Reputation: 12106

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

Upvotes: 0

nielsbot
nielsbot

Reputation: 16022

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

[ components setTimeZone:[ NSTimeZone systemTimeZone ] ] ;

Upvotes: 2

Related Questions