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