ios - UIDatePicker 不遵守夏令时

标签 ios swift nscalendar nsdatecomponents

我试图从 UIDatePicker 获取小时和分钟值以用于我的服务器,但 UIDatePicker 的值是一个小时。我本地的时区目前使用夏令时,所以我假设 UIDatePicker 不遵守这一点。

这是我用来将 UIDatePicker 提供的日期转换为其小时和分钟值的代码:

struct MyTimeSettings {

    var time: Date!

    init(from json: [String : Any]) {
        var calendar = Calendar.current
        calendar.timeZone = TimeZone(abbreviation: "UTC")!

        self.time = calendar.date(from: DateComponents(timeZone: TimeZone(abbreviation: "UTC")!, year: 0, month: 0, day: 0, hour: (json["Hour"] as! Int), minute: (json["Minute"] as! Int)))
    }

    init() {}

    func getJSON() -> [String : Any] {
        var calendar = Calendar.current
        calendar.timeZone = TimeZone(abbreviation: "UTC")!
        let components = calendar.dateComponents(in: TimeZone(abbreviation: "UTC")!, from: self.time)

        return [
            "Hour" : components.hour!,
            "Minute" : components.minute!
        ]
    }

    static func ==(lhs: MyTimeSettings, rhs: MyTimeSettings) -> Bool {
        return (lhs.time == rhs.time)
    }
}

为了测试它,我给了它一个 Date,计算结果为美国东部时间晚上 10:15:

var settings = MyTimeSettings()
let date = Date(timeIntervalSince1970: 1522894500)
settings.time = date

print(settings.getJSON()) // ["Hour": 2, "Minute": 15]

它也适用于输入 JSON:

let json = ["Hour": 2, "Minute": 15]
print(MyTimeSettings(from: json).getJSON()) // ["Hour": 2, "Minute": 15]

我的问题是相同的代码在从 UIDatePicker 获取日期时不能正常工作。我正在使用 Eureka用于在表格 View 单元格中显示 UIDatePicker 的库:

<<< TimePickerRow() { row in
    row.cell.datePicker.timeZone = TimeZone.current
    row.cell.datePicker.locale = Locale.current
    row.value = self.myTimeSettings.time
}.onChange({ (row) in
    self.myTimeSettings.time = row.value
})

然后我将日期选择器上的时间设置为晚上 10 点 15 分(美国东部时间),但我没有得到世界标准时间凌晨 2 点 15 分:

print(myTimeSettings.getJSON()) // ["Hour": 3, "Minute": 12]

为什么日期选择器返回错误的时间?

最佳答案

根据 Apple's Documentation你会想调用这个方法:

Declaration

func daylightSavingTimeOffset(for date: Date = default) -> TimeInterval

Parameters

date

The date to use for the calculation. The default value is the current date.

关于ios - UIDatePicker 不遵守夏令时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49650476/

相关文章:

ios - 如何确保线程安全地使用 "NSCalendar currentCalendar"?

ios - 需要更新 Swift 代码到最新版本

ios - 是否可以在Main.storyboard中添加UIAlertController和UIAlertAction

iphone - 我的 reloaddata 调用没有调用 UItableviewcontroller 中的委托(delegate)方法?

swift -++ 和 +=1 完全一样吗?

ios - 是否可以在基于文档的应用程序中使用 Core Data?

ios - 如何在 AppDelegate 之外注册推送通知?

swift - 检查日期何时过去 - Swift

swift - 制定一天的开始和结束。 swift

ios - UIView 高度未调整为 UITableView header 中的 subview 高度