I'm trying to use the solution provided in "NSDate for first day of the month" to get the first day of month.
My code is in a NSDate category:
- (NSDate *)firstDayInMonthOfDate {
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self];
comps.timeZone = calendar.timeZone;
NSDate *startDate;
[comps setDay:1];
startDate = [calendar dateFromComponents:comps];
return startDate;
}
This yields the last day of the previous month.... example:
self = date: 2013-11-02 22:00:00
comps = <NSDateComponents: 0x749b4c0>
TimeZone: Europe/Bucharest (GMT+03:00) offset 10800 (Daylight)
Calendar Year: 2013
Month: 11
Leap month: no
Day: 1
startDate = 2013-10-31 22:00:00 +0000
So, in order to get the correct day, I have to set comps.day = 2. I just don't understand where the extra 1 is coming from.
[EDIT] I want to use the dates for collection view cells, so I would like a reliable way to get the first date of the month, eg. 2013-11-01
[EDIT] Using a NSDateFormatter to print the date gives the correct result (2013-10-31). The problem with po and NSLog is that they don't interpret the timezone properly right (2012-12-31 10pm + 3h GMT != 2013-01-01 12am) I recomend a date programming tutorial: http://rypress.com/tutorials/objective-c/data-types/dates.html