Get firstdate, lastdate of month?

后端 未结 8 1026
不思量自难忘°
不思量自难忘° 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)
            }
    

提交回复
热议问题