Swift: Get correct time zone from Date Picker?

和自甴很熟 提交于 2020-05-28 04:48:18

问题


I am trying to get the correct time zone from the date picker in swift using time formatter, it's not working. I'm getting UTC, not EST.

1) If I print dateFormatter.stringFromDate(datePicker) I get EST, but

2) I don't need a string, I need an NSDate in EST so

3) I can use it to get the timeIntervalSinceDate(NSDate) in EST.

My trick of trying to take it from string back to NSDate as seen below didn't work. It's still in UTC and the time interval since date is not right.

dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.timeZone = NSTimeZone.localTimeZone()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date: NSDate = dateFormatter.dateFromString(dateFormatter.stringFromDate(datePicker))!
print(date)
print(date.timeIntervalSinceDate(datePicker))

回答1:


You cannot "get a time zone" from a date picker. You can just get a date. The date will be independent on the current time zone of the device.

Perhaps you think you have a different date, but actually, there is no such thing as a "UTC date" or "EST date". Instead, there is only one date, and you use date formatters to display them for various time zones.

Note that there is quite a bit of redundancy in your code. The default locale and time zone of a date formatter are already the same values that you set. Also, when you have a method that returns a NSDate you do not have annotate the constant with : NSDate, making your code more verbose and cluttered.

Note that if you print a date the console will always show UTC. e.g.

let date = NSDate() // Nov 10, 9:44 PM
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd hh:mm a"
let dateString = dateFormatter.stringFromDate(date) // "2015-11-10 09:44 PM"
print(date) // "2015-11-10 20:44:54 +0000\n"


来源:https://stackoverflow.com/questions/33639037/swift-get-correct-time-zone-from-date-picker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!