Swift: Get correct time zone from Date Picker?

10,743

Solution 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"

Solution 2

The above answer is totally wrong. Date picker report the date in system locale anytime, so, if the datePicker shows an 08:00 Time and you are GMT+2, the property date of the picker will be 06:00.

So for have the absolute value of the datePicker you have to pass to him the UTC time zone in view did load with:

datePicker.timeZone = TimeZone.init(identifier: "UTC")

Now, the date property of the picker will be the expected and choosen one.

Share:
10,743
Nathan McKaskle
Author by

Nathan McKaskle

Updated on June 05, 2022

Comments

  • Nathan McKaskle
    Nathan McKaskle almost 2 years

    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))
    
  • Nathan McKaskle
    Nathan McKaskle over 8 years
    Why am I getting weird time intervals since the date then? -0.5 seconds.
  • Mundi
    Mundi over 8 years
    You have not given any details about your time intervals. - Also, note that you are calling the time interval method on the datePicker, not the date.
  • Nathan McKaskle
    Nathan McKaskle over 3 years
    The above answer was from 5 years ago, I’ve no doubt everything has changed since that much earlier version of swift.