Swift 3 - 获取星期一的日期

时间:2017-02-23 05:31:36

标签: swift date

func GetMondayfromDate(_ date: Date) -> Date {
    var mdate: Date
    let calendar = Calendar(identifier: .iso8601)
    var components = calendar.dateComponents(in: TimeZone(identifier: "UTC")!, from: date)
    components.weekday = 1 //today is Thursday, but weekday == 5 ??
    mdate = calendar.date(from: components)!
    return mdate
}

试图获取星期一的日期,但这不起作用......

1 个答案:

答案 0 :(得分:4)

以下是 SWIFT 3 解决方案

信用:this

import Foundation

func getWeekDaysInEnglish() -> [String] {
let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
calendar.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
return calendar.weekdaySymbols
}

enum SearchDirection {
 case Next
 case Previous

  var calendarOptions: NSCalendar.Options {
     switch self {
     case .Next:
         return .matchNextTime
     case .Previous:
         return [.searchBackwards, .matchNextTime]
     }
  }
}

func get(direction: SearchDirection, _ dayName: String, considerToday consider: Bool = false) -> NSDate {
let weekdaysName = getWeekDaysInEnglish()

assert(weekdaysName.contains(dayName), "weekday symbol should be in form \(weekdaysName)")

let nextWeekDayIndex = weekdaysName.index(of: dayName)! + 1 // weekday is in form 1 ... 7 where as index is 0 ... 6

let today = NSDate()

let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!

if consider && calendar.component(.weekday, from: today as Date) == nextWeekDayIndex {
    return today
}

let nextDateComponent = NSDateComponents()
nextDateComponent.weekday = nextWeekDayIndex


let date = calendar.nextDate(after: today as Date, matching: nextDateComponent as DateComponents, options: direction.calendarOptions)
return date! as NSDate
}
get(direction: .Previous, "Monday", considerToday: true)
  

OUTPUT =“2017年2月20日,上午12:00”