I am trying to get the hour and minute values from a UIDatePicker
for use in my server, but the value from the UIDatePicker
is an hour off. My local timezone currently uses daylight savings time, so I'm assuming that the UIDatePicker
is not respecting that.
Here is the code I'm using to convert the date provided by the UIDatePicker
to its hour and minute values:
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)
}
}
To test it, I gave it a Date
which evaluates to 10:15 PM EDT:
var settings = MyTimeSettings()
let date = Date(timeIntervalSince1970: 1522894500)
settings.time = date
print(settings.getJSON()) // ["Hour": 2, "Minute": 15]
It also works properly with input JSON:
let json = ["Hour": 2, "Minute": 15]
print(MyTimeSettings(from: json).getJSON()) // ["Hour": 2, "Minute": 15]
My problem is that the same code does not work properly whilst getting the date from the UIDatePicker
. I am using the Eureka library for displaying the UIDatePicker
in a table view cell:
<<< 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
})
I then set the time on the date picker to 10:15 PM (EDT), but I do not get 2:15 AM UTC:
print(myTimeSettings.getJSON()) // ["Hour": 3, "Minute": 12]
Why is the date picker returning the wrong time?