Search code examples
swiftdatensdatensdateformatternstimezone

Getting Date object in Swift using full name timezone?


I want to get Date object using parameters. With time zone abbreviation and with identifier it is possible. But can we get with full name timezone string.

"dateTime": "2017-04-15T12:00:00",
"timeZone": "Pacific Standard Time"

Solution

  • This is certainly possible but not very simple. Let's just take all possible time zones and compare their localized description with the one you have:

    let dateString = "2017-04-15T12:00:00"
    let timeZoneName = "Pacific Standard Time"
    let locale = Locale(identifier: "en-US")
    
    let knownTimeZones = TimeZone.knownTimeZoneIdentifiers.flatMap { TimeZone(identifier: $0) }
    let timeZone = knownTimeZones.first {
         // I don't know what type of name you have, `.standard` does not have to be correct
         $0.localizedName(for: .standard, locale: locale) == timeZoneName
    }
    
    print(timeZone)
    
    if let timeZone = timeZone {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = locale
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        dateFormatter.timeZone = timeZone
    
        print(dateFormatter.date(from: dateString))
    }