Getting the last day of a month

前端 未结 9 726
别跟我提以往
别跟我提以往 2020-12-08 00:24

How can I get the last day of the current month as an NSDate?

相关标签:
9条回答
  • 2020-12-08 00:58

    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)!
        }
    }
    
    0 讨论(0)
  • 2020-12-08 01:01

    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;
    }
    
    0 讨论(0)
  • 2020-12-08 01:03
    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.

    0 讨论(0)
提交回复
热议问题