ios - Swift - 如何使用偏移选项将 UNIX 时间转换为工作日?

标签 ios swift

我正在尝试创建一个接受 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/

相关文章:

iOS:如何判断是否滚动到 UITableView 中的特定行?

ios - Swift 2 upgrade Swift 3 编译报错很多方法如willTransitionToTraitCollection :newCollection:withTransitionCoordinator

ios - 从解析查询 block 返回 UIImage 数组

ios - UITapGestureRecognizer 快速对 UIImageView 进行操作

ios - 是否应该通过storyboard/xib添加可选 View ,然后以编程方式隐藏或添加? (良好做法)

ios - cellForItemAtIndexPath 在强制滚动以使其可见后返回 nil

objective-c - 减少内存大小以确保 iOS 中的后台运行

iOS : Swift : Right and Left view controller transitions between mutiple view controllers

ios - 当我将函数更改为类 func 以在另一个 swift 文件中使用该函数时,对成员 tableView.reloadData() 的引用不明确

ios - XCode 9 在打开所有 Storyboard文件时崩溃