我想要获得周一的本周日期.这在我的表格视图中被视为一周的第一天.
我还需要获得本周的周日.在我的表视图中,这被视为一周的最后一天.
我还需要获得本周的周日.在我的表视图中,这被视为一周的最后一天.
目前的尝试:
let date = NSDate() let calendar = NSCalendar.currentCalendar() calendar.firstWeekday = 1 //attempt to changefirstday let dateFormatter = NSDateFormatter() let theDateFormat = NSDateFormatterStyle.ShortStyle let theTimeFormat = NSDateFormatterStyle.ShortStyle dateFormatter.dateStyle = theDateFormat dateFormatter.timeStyle = theTimeFormat let currentDateComponents = calendar.components([.YearForWeekOfYear,.WeekOfYear ],fromDate: date) let startOfWeek = calendar.dateFromComponents(currentDateComponents) print("startOfWeek is \(startOfWeek)") let stringDate = dateFormatter.stringFromDate(startOfWeek!) print("string date is \(stringDate)") //This is returning Sunday's date
解决方法
我写了日期扩展以获取特定工作日的日期,这里使用Swift 4是多么容易,
Date.today().next(.monday) // Feb 12,2018 at 12:00 AM Date.today().next(.sunday) // Feb 11,2018 at 12:00 AM Date.today().prevIoUs(.sunday) // Feb 4,2018 at 12:00 AM Date.today().prevIoUs(.monday) // Feb 5,2018 at 12:00 AM Date.today().prevIoUs(.thursday) // Feb 1,2018 at 12:00 AM Date.today().next(.thursday) // Feb 15,2018 at 12:00 AM Date.today().prevIoUs(.thursday,considerToday: true) // Feb 8,2018 at 11:04 PM Date.today().next(.monday) .next(.sunday) .next(.thursday) // Feb 22,2018 at 12:00 AM
这是Date扩展名,
extension Date { static func today() -> Date { return Date() } func next(_ weekday: Weekday,considerToday: Bool = false) -> Date { return get(.Next,weekday,considerToday: considerToday) } func prevIoUs(_ weekday: Weekday,considerToday: Bool = false) -> Date { return get(.PrevIoUs,considerToday: considerToday) } func get(_ direction: SearchDirection,_ weekDay: Weekday,considerToday consider: Bool = false) -> Date { let dayName = weekDay.rawValue let weekdaysName = getWeekDaysInEnglish().map { $0.lowercased() } assert(weekdaysName.contains(dayName),"weekday symbol should be in form \(weekdaysName)") let searchWeekdayIndex = weekdaysName.index(of: dayName)! + 1 let calendar = Calendar(identifier: .gregorian) if consider && calendar.component(.weekday,from: self) == searchWeekdayIndex { return self } var nextDateComponent = DateComponents() nextDateComponent.weekday = searchWeekdayIndex let date = calendar.nextDate(after: self,matching: nextDateComponent,matchingPolicy: .nextTime,direction: direction.calendarSearchDirection) return date! } } // MARK: Helper methods extension Date { func getWeekDaysInEnglish() -> [String] { var calendar = Calendar(identifier: .gregorian) calendar.locale = Locale(identifier: "en_US_POSIX") return calendar.weekdaySymbols } enum Weekday: String { case monday,tuesday,wednesday,thursday,friday,saturday,sunday } enum SearchDirection { case Next case PrevIoUs var calendarSearchDirection: Calendar.SearchDirection { switch self { case .Next: return .forward case .PrevIoUs: return .backward } } } }