我只需要使用一周中的某一天为当前一周(星期日-星期六)创建一个有效日期。
例如: 今天的日期是2020年9月17日。所以星期范围是9月13日星期日-9月19日星期六。
鉴于“星期二”,我需要将此字符串转换为:2020年9月15日,星期二,类型为日期。
我试图这样做,但是我想出了一个非常混乱,不可靠的解决方案。
非常感谢您的帮助。
答案 0 :(得分:1)
这就是我要做的:
let calendar = Calendar.current
var dateComponents = calendar.dateComponents([.year, .month, .weekOfYear], from: Date())
dateComponents.weekday = 1 // Figure out a way to map "Sunday" = 1, "Monday" = 2, etc..
let date = calendar.date(from: dateComponents)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy"
print(dateFormatter.string(from: date!)) // Sunday, September 13, 2020
我可能会考虑为平日创建一个枚举。您可以使用String值对其进行初始化,并具有返回其Int值的函数。
enum Weekday: Int {
case sunday = 1
case monday = 2
case tuesday = 3
case wednesday = 4
case thursday = 5
case friday = 6
case saturday = 7
init?(_ stringValue: String) {
switch stringValue {
case "Sunday":
self = .sunday
case "Monday":
self = .monday
case "Tuesday":
self = .tuesday
case "Wednesday":
self = .wednesday
case "Thursday":
self = .thursday
case "Friday":
self = .friday
case "Saturday":
self = .saturday
default:
return nil
}
}
}
然后使用它:
if let weekday = Weekday("Wednesday") {
// ... code above
dateComponents.weekday = weekday.rawValue
// ... some more code
}