End Date showing Wrong

2019-06-11 09:28发布

问题:

I want to find start date and end date of week I am geting start date but not find right end date of week

 startDate = NSDate().startOfWeek(2)
            print(startDate)
            endDate   = startDate.endOfWeek(3)
            print(endDate) 

I am getting this start date -2016-07-04 06:30:00 +0000 and end date - 5828963-12-20 00:00:00 +0000

extension NSDate {
    func startOfWeek(weekday: Int?) -> NSDate? {
        guard
            let cal: NSCalendar = NSCalendar.currentCalendar(),
            let comp: NSDateComponents = cal.components([.YearForWeekOfYear, .WeekOfYear], fromDate: self) else { return nil }
        comp.to12pm()
        cal.firstWeekday = weekday ?? 1
        return cal.dateFromComponents(comp)!
    }

    func endOfWeek(weekday: Int) -> NSDate? {
        guard
            let cal: NSCalendar = NSCalendar.currentCalendar(),
            let comp: NSDateComponents = cal.components([.WeekOfYear], fromDate: self) else { return nil }
        comp.weekOfYear = 1
        comp.day -= 1
        comp.to12pm()
        return cal.dateByAddingComponents(comp, toDate: self.startOfWeek(weekday)!, options: [])!
    }
}
internal extension NSDateComponents {
    func to12pm() {
        self.hour = 12
        self.minute = 0
        self.second = 0
    }
}

回答1:

extension NSDate {
    enum Weekday: Int {
        case Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
    }
    func startOfWeek(firstWeekday: Weekday = .Sunday) -> NSDate? {
        let calendar = NSCalendar.currentCalendar()
        let dateComponents = calendar.components([.YearForWeekOfYear, .WeekOfYear], fromDate: self)
        dateComponents.setTimeComponentsToNoon()
        calendar.firstWeekday = firstWeekday.rawValue
        return calendar.dateFromComponents(dateComponents)
    }
    func endOfWeek(firstWeekday: Weekday = .Sunday) -> NSDate? {
        guard let startOfWeek = startOfWeek(firstWeekday) else { return nil }
        let calendar = NSCalendar.currentCalendar()
        let dateComponents = NSDateComponents()
        dateComponents.weekOfYear = 1
        dateComponents.day = -1
        return calendar.dateByAddingComponents(dateComponents, toDate: startOfWeek, options: [])
    }
}
internal extension NSDateComponents {
    func setTimeComponentsToNoon() {
        self.hour = 12
        self.minute = 0
        self.second = 0
        self.nanosecond = 0
    }
}

Testing:

if let startDate = NSDate().startOfWeek(.Monday) ,
   endDate = NSDate().endOfWeek(.Monday) {
    print(startDate)  // "2016-07-04 15:00:00 +0000\n"
    print(endDate)    // "2016-07-10 15:00:00 +0000\n"
}
if let startDate = NSDate().startOfWeek() ,
    endDate = NSDate().endOfWeek() {
    print(startDate)  // "2016-07-03 15:00:00 +0000\n"
    print(endDate)    // "2016-07-09 15:00:00 +0000\n"
}