[ios] How to get a user's time zone?

Does anyone know of a way to get a users time zone in Swift?

I'm getting a specific time something is on t.v. out of a database and then need to subtract/add from where they are located to show them the correct time it's on.

This question is related to ios xcode swift macos nstimezone

The answer is


edit/update:

Xcode 8 or later • Swift 3 or later

var secondsFromGMT: Int { return TimeZone.current.secondsFromGMT() }
secondsFromGMT  // -7200

if you need the abbreviation:

var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "" }
localTimeZoneAbbreviation   // "GMT-2"

if you need the timezone identifier:

var localTimeZoneIdentifier: String { return TimeZone.current.identifier }

localTimeZoneIdentifier // "America/Sao_Paulo"

To know all timezones abbreviations available:

var timeZoneAbbreviations: [String:String] { return TimeZone.abbreviationDictionary }
timeZoneAbbreviations   // ["CEST": "Europe/Paris", "WEST": "Europe/Lisbon", "CDT": "America/Chicago", "EET": "Europe/Istanbul", "BRST": "America/Sao_Paulo", "EEST": "Europe/Istanbul", "CET": "Europe/Paris", "MSD": "Europe/Moscow", "MST": "America/Denver", "KST": "Asia/Seoul", "PET": "America/Lima", "NZDT": "Pacific/Auckland", "CLT": "America/Santiago", "HST": "Pacific/Honolulu", "MDT": "America/Denver", "NZST": "Pacific/Auckland", "COT": "America/Bogota", "CST": "America/Chicago", "SGT": "Asia/Singapore", "CAT": "Africa/Harare", "BRT": "America/Sao_Paulo", "WET": "Europe/Lisbon", "IST": "Asia/Calcutta", "HKT": "Asia/Hong_Kong", "GST": "Asia/Dubai", "EDT": "America/New_York", "WIT": "Asia/Jakarta", "UTC": "UTC", "JST": "Asia/Tokyo", "IRST": "Asia/Tehran", "PHT": "Asia/Manila", "AKDT": "America/Juneau", "BST": "Europe/London", "PST": "America/Los_Angeles", "ART": "America/Argentina/Buenos_Aires", "PDT": "America/Los_Angeles", "WAT": "Africa/Lagos", "EST": "America/New_York", "BDT": "Asia/Dhaka", "CLST": "America/Santiago", "AKST": "America/Juneau", "ADT": "America/Halifax", "AST": "America/Halifax", "PKT": "Asia/Karachi", "GMT": "GMT", "ICT": "Asia/Bangkok", "MSK": "Europe/Moscow", "EAT": "Africa/Addis_Ababa"]

To know all timezones names (identifiers) available:

var timeZoneIdentifiers: [String] { return TimeZone.knownTimeZoneIdentifiers }
timeZoneIdentifiers           // ["Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers", "Africa/Asmara", "Africa/Bamako", "Africa/Bangui", "Africa/Banjul", "Africa/Bissau", "Africa/Blantyre", "Africa/Brazzaville", "Africa/Bujumbura", "Africa/Cairo", "Africa/Casablanca", "Africa/Ceuta", "Africa/Conakry", "Africa/Dakar", "Africa/Dar_es_Salaam", "Africa/Djibouti", "Africa/Douala", "Africa/El_Aaiun", "Africa/Freetown", "Africa/Gaborone", "Africa/Harare", "Africa/Johannesburg", "Africa/Juba", "Africa/Kampala", "Africa/Khartoum", "Africa/Kigali", "Africa/Kinshasa", "Africa/Lagos", "Africa/Libreville", "Africa/Lome", "Africa/Luanda", "Africa/Lubumbashi", "Africa/Lusaka", "Africa/Malabo", "Africa/Maputo", "Africa/Maseru", "Africa/Mbabane", "Africa/Mogadishu", "Africa/Monrovia", "Africa/Nairobi", "Africa/Ndjamena", "Africa/Niamey", "Africa/Nouakchott", "Africa/Ouagadougou", "Africa/Porto-Novo", "Africa/Sao_Tome", "Africa/Tripoli", "Africa/Tunis", "Africa/Windhoek", "America/Adak", "America/Anchorage", "America/Anguilla", "America/Antigua", "America/Araguaina", "America/Argentina/Buenos_Aires", "America/Argentina/Catamarca", "America/Argentina/Cordoba", "America/Argentina/Jujuy", "America/Argentina/La_Rioja", "America/Argentina/Mendoza", "America/Argentina/Rio_Gallegos", "America/Argentina/Salta", "America/Argentina/San_Juan", "America/Argentina/San_Luis", "America/Argentina/Tucuman", "America/Argentina/Ushuaia", "America/Aruba", "America/Asuncion", "America/Atikokan", "America/Bahia", "America/Bahia_Banderas", "America/Barbados", "America/Belem", "America/Belize", "America/Blanc-Sablon", "America/Boa_Vista", "America/Bogota", …, "Pacific/Marquesas", "Pacific/Midway", "Pacific/Nauru", "Pacific/Niue", "Pacific/Norfolk", "Pacific/Noumea", "Pacific/Pago_Pago", "Pacific/Palau", "Pacific/Pitcairn", "Pacific/Pohnpei", "Pacific/Ponape", "Pacific/Port_Moresby", "Pacific/Rarotonga", "Pacific/Saipan", "Pacific/Tahiti", "Pacific/Tarawa", "Pacific/Tongatapu", "Pacific/Truk", "Pacific/Wake", "Pacific/Wallis"]

There is a few other info you may need:

var isDaylightSavingTime: Bool { return TimeZone.current.isDaylightSavingTime(for: Date()) }
print(isDaylightSavingTime) // true (in effect)

var daylightSavingTimeOffset: TimeInterval { return TimeZone.current.daylightSavingTimeOffset() }
print(daylightSavingTimeOffset)  // 3600 seconds (1 hour - daylight savings time)


var nextDaylightSavingTimeTransition: Date? { return TimeZone.current.nextDaylightSavingTimeTransition }    //  "Feb 18, 2017, 11:00 PM"
 print(nextDaylightSavingTimeTransition?.description(with: .current) ?? "none")
nextDaylightSavingTimeTransition   // "Saturday, February 18, 2017 at 11:00:00 PM Brasilia Standard Time\n"

var nextDaylightSavingTimeTransitionAfterNext: Date? {
    guard
        let nextDaylightSavingTimeTransition = nextDaylightSavingTimeTransition
        else { return nil }
    return TimeZone.current.nextDaylightSavingTimeTransition(after: nextDaylightSavingTimeTransition)
}

nextDaylightSavingTimeTransitionAfterNext  //   "Oct 15, 2017, 1:00 AM"

TimeZone - Apple Developer Swift Documentation


func getCurrentTimeZone() -> String {
        let localTimeZoneAbbreviation: Int = TimeZone.current.secondsFromGMT()
        let gmtAbbreviation = (localTimeZoneAbbreviation / 60)
        return "\(gmtAbbreviation)"
}

You can get current time zone abbreviation.


Swift 4, 4.2 & 5

var timeZone : String = String()

override func viewDidLoad() {
    super.viewDidLoad()
    timeZone = getCurrentTimeZone()
    print(timeZone)
}

func getCurrentTimeZone() -> String {
        let localTimeZoneAbbreviation: Int = TimeZone.current.secondsFromGMT()
        let items = (localTimeZoneAbbreviation / 3600)
        return "\(items)"
}

Xcode 8.2.1 • Swift 3.0.2

Locale.availableIdentifiers
Locale.isoRegionCodes
Locale.isoCurrencyCodes
Locale.isoLanguageCodes
Locale.commonISOCurrencyCodes

Locale.current.regionCode           // "US"
Locale.current.languageCode         // "en"
Locale.current.currencyCode         // "USD"
Locale.current.currencySymbol       // "$"
Locale.current.groupingSeparator    // ","
Locale.current.decimalSeparator     // "."
Locale.current.usesMetricSystem     // false

Locale.windowsLocaleCode(fromIdentifier: "pt_BR")                   //  1,046
Locale.identifier(fromWindowsLocaleCode: 1046) ?? ""                // "pt_BR"
Locale.windowsLocaleCode(fromIdentifier: Locale.current.identifier) //  1,033 Note: I am in Brasil but I use "en_US" format with all my devices
Locale.windowsLocaleCode(fromIdentifier: "en_US")                                   // 1,033
Locale.identifier(fromWindowsLocaleCode: 1033) ?? ""                                // "en_US"

Locale(identifier: "en_US_POSIX").localizedString(forLanguageCode: "pt")            // "Portuguese"
Locale(identifier: "en_US_POSIX").localizedString(forRegionCode: "br")              // "Brazil"
Locale(identifier: "en_US_POSIX").localizedString(forIdentifier: "pt_BR")           // "Portuguese (Brazil)"

TimeZone.current.localizedName(for: .standard, locale: .current) ?? ""              // "Brasilia Standard Time"
TimeZone.current.localizedName(for: .shortStandard, locale: .current) ?? ""         // "GMT-3
TimeZone.current.localizedName(for: .daylightSaving, locale: .current) ?? ""        // "Brasilia Summer Time"
TimeZone.current.localizedName(for: .shortDaylightSaving, locale: .current) ?? ""   // "GMT-2"
TimeZone.current.localizedName(for: .generic, locale: .current) ?? ""               // "Brasilia Time"
TimeZone.current.localizedName(for: .shortGeneric, locale: .current) ?? ""          // "Sao Paulo Time"

var timeZone: String {
    return TimeZone.current.localizedName(for: TimeZone.current.isDaylightSavingTime() ?
                                               .daylightSaving :
                                               .standard,
                                          locale: .current) ?? "" }

timeZone       // "Brasilia Summer Time"

You can use below code for getting current time zone

 func getCurrentTimeZone() -> String{

         return TimeZone.current.identifier

  }

  let currentTimeZone = getCurrentTimeZone()
   print(currentTimeZone)

NSTimeZone *timeZone = [NSTimeZone localTimeZone];
NSString *tzName = [timeZone name];

The name will be something like "Australia/Sydney", or "Europe/Lisbon".

Since it sounds like you might only care about the continent, that might be all you need.


Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to xcode

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64 iPhone is not available. Please reconnect the device Make a VStack fill the width of the screen in SwiftUI error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65 The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1 Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Xcode 10: A valid provisioning profile for this executable was not found Xcode 10, Command CodeSign failed with a nonzero exit code

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to macos

Problems with installation of Google App Engine SDK for php in OS X dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac Could not install packages due to an EnvironmentError: [Errno 13] How do I install Java on Mac OSX allowing version switching? Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Can't compile C program on a Mac after upgrade to Mojave You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user) How can I install a previous version of Python 3 in macOS using homebrew? Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

Examples related to nstimezone

How to get a user's time zone?