我正在尝试创建一个接受 unix 时间、时区和整数的函数。希望返回正确的工作日(星期一等)。
func unixTimeToWeekday(unixTime: Double, timeZone: String, offset: Int) -> String {
if(timeZone == "" || unixTime == 0.0) {
return ""
} else {
let time = Date(timeIntervalSince1970: unixTime)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(identifier: timeZone)
dateFormatter.locale = Locale(identifier: NSLocale.system.identifier)
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: time)
}
}
我在实现偏移部分时遇到问题。我希望像这样使用它...
如果今天是星期一,那么
unixTimeToWeekday(unixTime: currentUnixTime, timezone: "America/New_York", offset: 1)
应返回“星期二”
和
unixTimeToWeekday(unixTime: currentUnixTime, timezone: "America/New_York", offset: 2)
应返回“星期三”等。
任何事情都有帮助。谢谢。
最佳答案
您不需要 DateFormatter。使用日历。
func unixTimeToWeekday(unixTime: Double, timeZone: String, offset: Int) -> String {
if(timeZone == "" || unixTime == 0.0) {
return ""
} else {
let time = Date(timeIntervalSince1970: unixTime)
var cal = Calendar(identifier: .gregorian)
if let tz = TimeZone(identifier: timeZone) {
cal.timeZone = tz
}
// Get the weekday for the given timezone.
// Add the offset
// Subtract 1 to convert from 1-7 to 0-6
// Normalize to 0-6 using % 7
let weekday = (cal.component(.weekday, from: time) + offset - 1) % 7
// Get the weekday name for the user's locale
return Calendar.current.weekdaySymbols[weekday]
}
}
print(unixTimeToWeekday(unixTime: 1530676380, timeZone: "America/New_York", offset: 0))
print(unixTimeToWeekday(unixTime: 1530676380, timeZone: "America/New_York", offset: 1))
输出:
Tuesday
Wednesday
自 1530676380
为 2018 年 7 月 3 日 23:53:00 EDT(星期二)起。
关于ios - Swift - 如何使用偏移选项将 UNIX 时间转换为工作日?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51165343/