【问题标题】:Swift 3 - Get the date of Monday [duplicate]Swift 3 - 获取星期一的日期[重复]
【发布时间】:2017-02-23 05:31:36
【问题描述】:
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
}

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

【问题讨论】:

标签: swift date


【解决方案1】:

这里是 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)

输出 =“2017 年 2 月 20 日,凌晨 12:00”

【讨论】:

  • 谢谢,我找到了解决办法!
  • 如果从这里找到解决方案,请接受答案。
  • @Anton 现在你也可以解决你以前的问题了。抱歉昨天没能回答。
  • 是的,我快完成了!
  • 很高兴知道这一点
猜你喜欢
  • 2015-08-31
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 2017-05-02
  • 2011-02-26
  • 1970-01-01
  • 1970-01-01
  • 2014-07-24
相关资源
最近更新 更多