我还需要获得本周的周日.在我的表视图中,这被视为一周的最后一天.
目前的尝试:
let date = NSDate()let calendar = NSCalendar.currentCalendar()calendar.firstWeekday = 1//attempt to changefirstdaylet dateFormatter = NSDateFormatter()let theDateFormat = NSDateFormatterStyle.ShortStylelet theTimeFormat = NSDateFormatterStyle.ShortStyledateFormatter.dateStyle = theDateFormatdateFormatter.timeStyle = theTimeFormatlet 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 AMDate.today().next(.sunday) // Feb 11,2018 at 12:00 AMDate.today().prevIoUs(.sunday) // Feb 4,2018 at 12:00 AMDate.today().prevIoUs(.monday) // Feb 5,2018 at 12:00 AMDate.today().prevIoUs(.thursday) // Feb 1,2018 at 12:00 AMDate.today().next(.thursday) // Feb 15,2018 at 12:00 AMDate.today().prevIoUs(.thursday,consIDerToday: true) // Feb 8,2018 at 11:04 PMDate.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 { .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 methodsextension 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 } } }}总结
以上是内存溢出为你收集整理的如何快速获得本周的本周日期全部内容,希望文章能够帮你解决如何快速获得本周的本周日期所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)