Get first day in a month from NSCalendar

bogen picture bogen · Feb 28, 2013 · Viewed 7.3k times · Source

I have this subset of a method that needs to get day one of the current month.

NSDate *today = [NSDate date];  // returns correctly 28 february 2013
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *dayOneInCurrentMonth = [gregorian dateByAddingComponents:components toDate:today options:0];

dayOneInCurrentMonth then prints out 2013-03-01 09:53:49 +0000, the first day of the next month.

How do I get day one of the current month?

Answer

Fabian Kreiser picture Fabian Kreiser · Feb 28, 2013

Your logic is wrong: Instead of setting the date's day to 1, you're adding a day to the current date.

Try something like that:

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:today];
components.day = 1;

NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];