views:

122

answers:

1

This is quite a simple concept, but as of yet I have been unable to find an elegant (and calendar locale independent) solution. I need to find the first day of the month for an arbitrary NSDate. For example, given an arbitrary NSDate (arbitraryDate) another NSDate object will be returned (let's call this firstDayOfMonthDate) which represents the first day of the month in arbitraryDate. The time component does not matter, as I just need the NSDate object for the first day of the month (although for neatness it would be useful if the time was just zeroed out).

Thanks in advance for any assistance.

+3  A: 

A possible solution:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:arbitraryDate];
[comp setDay:1];
NSDate *firstDayOfMonthDate = [gregorian dateFromComponents:comp];
diciu
Thanks for your suggestion. However, this will only work with the Gregorian calendar. Is it possible to make it calendar locale/format independent, as I would like the app I am building to work across all calendar formats supported on the iPhone?
Skoota
you can use [NSCalendar currentCalendar]
diciu
Thanks mate. Working perfectly.
Skoota