How to create US Central timezone in Swift?

The server I'm working with returns a date/time string that is always expressed in US central time. There is no timezone information in the string itself.

In order to parse this string, I need to create a DateFormatter and then assign its timeZone property.

I'm having trouble figuring out the right way to do this. I know that the correct string that means US central time is "America/Chicago", but it appears that the TimeZone initializer is looking for an abbreviation, rather than a full string.

I don't know what the correct abbreviation is. I don't want to use "CST" or "CDT" since those denote standard or daylight time. I need something that means whatever the current timzeone is in Chicago.

In Java, as an example, the Timezone class accepts "America/Chicago" as an initializer and it works whether or not the calendar is on daylight savings time.

Thanks, Frank

Did you try:

let chicagoTimezoneName = NSTimeZone.knownTimeZoneNames().filter { $0.containsString("Chicago")  }.first
dateFormatter.timeZone = NSTimeZone(name: chicagoTimezoneName!)

Seen from https://stackoverflow.com/questions/9761847/where-can-i-find-a-list-of-timezones

it appears that the TimeZone initializer is looking for an abbreviation, rather than a full string.

I do not understand why you think so. As far as I tried, "America/Chicago" returned the thing you would like:

if let tz = TimeZone(identifier: "America/Chicago") {
    print(tz) //-> America/Chicago (fixed)
    print(tz.identifier) //-> America/Chicago
    print(tz.abbreviation(for: Date())) //-> Optional("CDT")
    print(tz.isDaylightSavingTime()) //-> true
    print(tz.secondsFromGMT()) //-> -18000
} else {
    print("Unknown TimeZone identifier")
}

Or you can write some Swift 5 version of the code shown by Claude31:

if let chicagoTimezoneIdentifier = TimeZone.knownTimeZoneIdentifiers.filter({ $0.contains("Chicago")  }).first,
   let chicagoTimezone = TimeZone(identifier: chicagoTimezoneIdentifier) {
    print(chicagoTimezone) //-> America/Chicago (fixed)
    //...
}
How to create US Central timezone in Swift?
 
 
Q