Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first day in a month from NSCalendar

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?

like image 646
bogen Avatar asked Feb 28 '13 10:02

bogen


2 Answers

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];
like image 81
Fabian Kreiser Avatar answered Oct 31 '22 03:10

Fabian Kreiser


You want [NSCalender dateFromComponents:] instead:

NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];
like image 1
trojanfoe Avatar answered Oct 31 '22 03:10

trojanfoe