Get firstdate, lastdate of month?

后端 未结 8 1006
不思量自难忘°
不思量自难忘° 2021-02-01 21:29

I want to get firstdate、lastdate of month,I try

NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
[components setDay:1];
self.c         


        
相关标签:
8条回答
  • 2021-02-01 22:19

    In Swift based in Nazir's answer

            func getFirstAndLastDateOfMonth(date: NSDate) -> (fistDateOfMonth: NSDate, lastDateOfMonth: NSDate) {
    
                let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
                let calendarUnits = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth
                let dateComponents = calendar?.components(calendarUnits, fromDate: date)
    
                let fistDateOfMonth = self.returnedDateForMonth(dateComponents!.month, year: dateComponents!.year, day: 1)
                let lastDateOfMonth = self.returnedDateForMonth(dateComponents!.month + 1, year: dateComponents!.year, day: 0)
    
                println("fistDateOfMonth \(fistDateOfMonth)")
                println("lastDateOfMonth \(lastDateOfMonth)")
    
                return (fistDateOfMonth!,lastDateOfMonth!)
            }
    
           func returnedDateForMonth(month: NSInteger, year: NSInteger, day: NSInteger) -> NSDate? {
                var components = NSDateComponents()
                components.day = day
                components.month = month
                components.year = year
    
                let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
    
                return gregorian!.dateFromComponents(components)
            }
    
    0 讨论(0)
  • 2021-02-01 22:27

    Ok, since I'm rolling my own calendar control, I went ahead and created a NSCalendar category. Here's my lastOfMonth method:

    - (NSDate *)lastOfMonth:(NSDate *)date
    {
        NSDateComponents *dc = [self components:NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit fromDate:date];
    
        NSRange dim = [self rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
        dc.day = dim.length;
    
        return [self dateFromComponents:dc];
    }
    
    0 讨论(0)
提交回复
热议问题