Getting the last day of a month
How can I get the last day of the current month as an NSDate
?
Solution 1:
NSDate *curDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curDate]; // Get necessary date components
// set last of month
[comps setMonth:[comps month]+1];
[comps setDay:0];
NSDate *tDateMonth = [calendar dateFromComponents:comps];
NSLog(@"%@", tDateMonth);
should also work.
Solution 2:
// Adapted from running code in my app
NSDate *curDate = [NSDate date];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSRange daysRange =
[currentCalendar
rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:curDate];
// daysRange.length will contain the number of the last day
// of the month containing curDate
NSLog(@"%i", daysRange.length);
Solution 3:
Put this in a category:
-(NSDate*)lastDayOfMonth
{
NSInteger dayCount = [self numberOfDaysInMonthCount];
NSDateComponents *comp = [[self calendar] components:
NSCalendarUnitYear |
NSCalendarUnitMonth |
NSCalendarUnitDay fromDate:self];
[comp setDay:dayCount];
return [[self calendar] dateFromComponents:comp];
}
-(NSInteger)numberOfDaysInMonthCount
{
NSRange dayRange = [[self calendar] rangeOfUnit:NSCalendarUnitDay
inUnit:NSCalendarUnitMonth
forDate:self];
return dayRange.length;
}
-(NSCalendar*)calendar
{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:TIMEZONE]];
return calendar;
}
Solution 4:
Swift version
extension NSDate {
func lastDayOfMonth() -> NSDate {
let calendar = NSCalendar.currentCalendar()
let dayRange = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: self)
let dayCount = dayRange.length
let comp = calendar.components([.Year, .Month, .Day], fromDate: self)
comp.day = dayCount
return calendar.dateFromComponents(comp)!
}
}