Get firstdate, lastdate of month?

后端 未结 8 1160
不思量自难忘°
不思量自难忘° 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:04

    For Swift 2.0 to get the first day of the current month:

        let date = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let dateComponents = calendar.components([NSCalendarUnit.Month, NSCalendarUnit.Year], fromDate: date)
        let firstDay = self.returnDateForMonth(dateComponents.month, year: dateComponents.year, day: 1)
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MMM-yy"
    
        print("First day of this month: \(firstDay)") // 01-Sep-15
    

    And the function to do this:

     func returnDateForMonth(month:NSInteger, year:NSInteger, day:NSInteger)->NSDate{
        let comp = NSDateComponents()
        comp.month = month
        comp.year = year
        comp.day = day
    
        let grego = NSCalendar.currentCalendar()
        return grego.dateFromComponents(comp)!
    }
    

提交回复
热议问题