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
NSCalend
Easy Way to get first and last date of previous month is :
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
Easy way of getting to the 1st from a given date:
NSDate *first = [gregorian dateBySettingUnit:NSCalendarUnitDay value:1 ofDate:date options:0];
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];
NSDate *startDate = nil;
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitMonth startDate:&startDate interval:NULL forDate:date];
return startDate;
By creating new variable is expensive on memory usage, it's better using date formatter 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]];
You want [NSCalender dateFromComponents:]
instead:
NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];