gpt4 book ai didi

ios - UIDatePicker 不遵守夏令时

转载 作者:行者123 更新时间:2023-11-28 06:01:13 25 4
gpt4 key购买 nike

我试图从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com