153

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.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Keith
  • 1,969
  • 4
  • 17
  • 27

7 Answers7

371

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

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Sorry to jump back in but do you know of a way to print out the name without the abbreviation? I looked through the docs but only found the obj c timeZoneWithName? Thanks. – Keith Dec 02 '14 at 00:18
  • 1
    Sure. I've posted it. It is almost the same but without the exclamation mark because it is not an optional. Declaration SWIFT var abbreviation: String? { get } and Declaration SWIFT var name: String { get } // without the question mark "?" – Leo Dabus Dec 02 '14 at 00:29
  • 1
    Fantastic! I was trying .description, I didn't think of .name. Those all will be really helpful. – Keith Dec 02 '14 at 16:59
  • Just now I got error on Xcode 8: Type 'TimeZone' has no member 'local' – Alexey Ishkov Aug 09 '16 at 23:45
  • yes, it is Swift 3 which does not have localTimeZone too. We should use 'current' instead. Like 'let local = TimeZone.current.secondsFromGMT' – Alexey Ishkov Aug 09 '16 at 23:53
  • Xcode version 8.0 beta 4 (8S188o) has 'CURRENT' instead of all your variants: /// The time zone currently used by the system. public static var current: TimeZone { get } – Alexey Ishkov Aug 09 '16 at 23:57
  • `TimeZone.current.identifier` doesn't return country and city anymore, instead I get `"Etc/GMT-3"`. Any idea how to get `Country/City` format? – Soberman Jun 01 '18 at 21:04
  • @Soberman I don't know why you are getting those results I still get "America/Sao_Paulo" here – Leo Dabus Jun 01 '18 at 21:17
  • @LeoDabus Do you have your timezone set to automatically on? – Soberman Jun 01 '18 at 21:39
  • 1
    Alright, I have figured it out - iPhone needs carrier services to get the data about where you are. In case you turn all that off - you won't get the city and country. Or if you are in roaming in another country. All this kinda sucks. – Soberman Jun 01 '18 at 22:31
  • When I use -> localTimeZoneAbbreviation // "GMT-2" in nowComponents.timeZone = TimeZone(abbreviation: localTimeZoneAbbreviation)! my App crashes – Markus Jul 03 '18 at 17:25
  • Why not simply `nowComponents.timeZone = .current` ? – Leo Dabus Jul 03 '18 at 17:27
  • Just call this method and it will return you a string type of time zone. func getCurrentTimeZone() -> String { let localTimeZoneAbbreviation: Int = TimeZone.current.secondsFromGMT() let items = (localTimeZoneAbbreviation / 3600) return "\(items)" } – Akbar Khan Jul 30 '19 at 11:11
  • 1
    This is exactly why we have Stackoverflow ! Thanks a ton mate :) – Tilak Madichetti Feb 24 '20 at 20:03
  • for me while running the code in Simulator it gives as GMT+5:30 and when in iphone it shows IST how to get timezone value as +0530 – Dark_Clouds_369 May 13 '22 at 08:04
28

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"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
16

You can use below code for getting current time zone

func getCurrentTimeZone() -> String {
    TimeZone.current.identifier
}

let currentTimeZone = getCurrentTimeZone()
print(currentTimeZone)
budiDino
  • 13,044
  • 8
  • 95
  • 91
Pankaj Jangid
  • 812
  • 9
  • 18
8

Objective-C

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

Swift

let tzName = TimeZone.current.identifier

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.

Abhishek Thapliyal
  • 3,497
  • 6
  • 30
  • 69
2

Swift 4, 4.2 & 5

var gmtHoursOffset : String = String()
    
override func viewDidLoad() {
    super.viewDidLoad()
    gmtHoursOffset = getHoursFromGmt()
    print(gmtHoursOffset)
}

func getHoursFromGmt() -> String {
    let secondsFromGmt: Int = TimeZone.current.secondsFromGMT()
    let hoursFromGmt = (secondsFromGmt / 3600)
    return "\(hoursFromGmt)"
}
Chris Kobrzak
  • 1,044
  • 14
  • 20
Akbar Khan
  • 2,215
  • 19
  • 27
1

To retrieve the current user time zone, use the code below.

TimeZone.current.abbreviation()!

Other Date Formate here.

OUTPUT:

enter image description here

Ole Pannier
  • 3,208
  • 9
  • 22
  • 33
  • This should be the accepted answer. Btw remove `.abbreviation()!` that converts it into a string – Arturo Nov 29 '21 at 21:28
0
func getCurrentTimeZone() -> String {
        let localTimeZoneAbbreviation: Int = TimeZone.current.secondsFromGMT()
        let gmtAbbreviation = (localTimeZoneAbbreviation / 60)
        return "\(gmtAbbreviation)"
}

You can get current time zone abbreviation.

Paresh. P
  • 486
  • 5
  • 18