Get the first day of the month from NSCalendar

I have this subset of the method that one day of the current month should receive.

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 issues 2013-03-01 09:53:49 +0000 , the first day of the next month.

How do I get the first day of the current month?

+7
source share
6 answers

Your logic is wrong: instead of setting the day of the day to 1, you add the day to the current date.

Try something like this:

 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]; 
+16
source

Instead, you want [NSCalender dateFromComponents:] :

 NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components]; 
+1
source

Easy way to get to the 1st from a specific date:

 NSDate *first = [gregorian dateBySettingUnit:NSCalendarUnitDay value:1 ofDate:date options:0]; 
+1
source

A simple way to get the first and last date of the previous month:

 NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; NSDateComponents *comp = [gregorian components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay ) fromDate:[NSDate date]]; //TO GET PREVIOUS MONTH LAST DAY [comp setMonth:[comp month]]; [comp setDay:1]; NSDate *tDateMonth = [gregorian dateFromComponents:comp]; NSLog(@"LAST DAY OF PREVIOUS MONTH ; %@", tDateMonth); //TO GET PREVIOUS MONTH FIRST DAY [comp setMonth:[comp month]-1]; [comp setDay:3]; NSDate *td = [gregorian dateFromComponents:comp]; NSLog(@"FIRST DAY OF PREVIOUS MONTH ; %@", td); 

Hope this helps

+1
source

When creating a new variable costly to use memory, it is best to use the date format to get the first day of the current month.

 today = [NSDate date]; firstDayDateFormatter = [[NSDateFormatter alloc] init]; [firstDayDateFormatter setDateFormat:@"01-MM-yyyy"]; dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"dd-MM-yyyy"]; [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]]; firstDayOfTheMonth = [mdfDateFormat dateFromString:[firstDayDateFormatter stringFromDate:today]]; 
0
source
 NSDate *startDate = nil; [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitMonth startDate:&startDate interval:NULL forDate:date]; return startDate; 
0
source

All Articles