NSDate for first day of the month

后端 未结 5 722
你的背包
你的背包 2020-12-30 23:09

This is quite a simple concept, but as of yet I have been unable to find an elegant (and calendar locale independent) solution. I need to find the first day of the month for

5条回答
  •  Happy的楠姐
    2020-12-30 23:38

    Swift 3

    I've included getting the last day of the month in case it is useful to anyone.

    extension Date {
        func lastDayOfMonth() -> Date {
            let calendar = Calendar.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)!
        }
    
        func firstDayOfMonth() -> Date {
            let calendar: Calendar = Calendar.current
            var components: DateComponents = calendar.dateComponents([.year, .month, .day], from: self)
            components.setValue(1, for: .day)
            return calendar.date(from: components)!
        }
    }
    

提交回复
热议问题