How can I get the last day of the current month as an NSDate
?
Swift 3.0.1 Version
extension Date {
func lastDayOfMonth() -> Date {
let calendar = NSCalendar.current
let dayRange = calendar.range(of: .day, in: .month, for: self)
let dayCount = dayRange?.count
var comp = calendar.dateComponents([.year, .month, .day], from: self)
comp.day = dayCount
return calendar.date(from: comp)!
}
}
Workaround Function:
-(int)GetLastDayOfMonth:(NSDate *)date
{
int last_day = 27;
NSCalendar *cal=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *compsMonth = [cal components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date];
[compsMonth setDay:last_day];
int month = [compsMonth month];
while(TRUE){
[compsMonth setDay:last_day+1];
NSDate *dateFuture = [cal dateFromComponents:compsMonth];
NSDateComponents *futureComps = [cal components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:dateFuture];
if(month != [futureComps month]){
return last_day;
}
last_day+=1;
}
return last_day;
}
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.