结束日期显示错误

时间:2016-07-08 04:56:10

标签: iphone swift ios9

我想查找开始日期和结束日期,我正在确定开始日期,但找不到正确的结束日期

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

我的开始日期为-2016-07-04 06:30:00 +0000和结束日期 - 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 个答案:

答案 0 :(得分:0)

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
    }
}

测试:

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"
}