Swift - 获取星期几的地点

时间:2016-09-26 04:28:31

标签: swift

如何从明天到今天前一天获得一周的一天。例如,如果今天是星期一,我需要在周二,周三,直到周日。有人可以指导我如何实现这个目标吗?

由于

1 个答案:

答案 0 :(得分:3)

有几种方法可以执行此操作,具体取决于您希望输出的格式。假设您想要按顺序排列整数数组,可以使用:

let today = Date()
let gregorian = Calendar(identifier: .gregorian)
let dateComponents = gregorian.dateComponents([.weekday], from: today)
let todaysWeekday = dateComponents.weekday!
var otherWeekdays: [Int] = []
for i in 1...6 {
    otherWeekdays.append((todaysWeekday - 1 + i) % 7 + 1)
}
// assuming today = 2 (Monday), otherWeekdays will contain [3, 4, 5, 6, 7, 1]

如果您还想要一个包含日期名称的字符串数组,那么如果您不关心本地化,则可以进行简单的查找。

let weekdayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
let otherWeekdayStrings = otherWeekdays.map({weekdayNames[$0 - 1]})
// otherweekdayStrings will contain ["Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

如果需要强大的本地化并且您只需要字符串,则可以使用DateFormatter并执行以下操作:

let today = Date()
let formatter = DateFormatter()
formatter.dateFormat = "EEEE"
var otherweekdayStrings: [String] = []
for i in 1...6 {
    let timeIntervalToAdd = TimeInterval(i * 86400)
    otherweekdayStrings.append(formatter.string(from: today.addingTimeInterval(timeIntervalToAdd)))
}
// Same output as previous