如何获取用户的时区?


116

有人知道在Swift中获取用户时区的方法吗?

我正在从数据库中取出电视上的特定时间,然后需要从它们所在的位置减去/添加,以向他们显示正确的时间。

Answers:


290

编辑/更新:

Xcode 8或更高版本•Swift 3或更高版本

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

如果需要缩写:

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

如果您需要时区标识符:

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

localTimeZoneIdentifier // "America/Sao_Paulo"

要了解所有可用的时区缩写:

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

要了解所有可用的时区名称(标识符):

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

您可能还需要一些其他信息:

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开发人员Swift文档


抱歉,我跳回来了,但是您知道不使用缩写打印名称的方法吗?我浏览了文档,但只发现obj c timeZoneWithName?谢谢。
基思(Keith)

1
当然。我已经贴了 它几乎相同,但是没有感叹号,因为它不是可选的。声明SWIFT var的缩写:字符串?{get}和声明SWIFT变量名称:字符串{get} //不带问号“?”
Leo Dabus 2014年

1
太棒了!我正在尝试.description,但我没有想到.name。这些都会非常有帮助。
基思

1
好吧,我已经弄清楚了-iPhone需要运营商服务来获取有关您的位置的数据。万一您关闭所有功能,您将不会得到城市和国家。或者,如果您正在另一个国家漫游。所有这些都糟透了。
Soberman '18

1
这正是我们拥有Stackoverflow的原因!感谢吨伴侣:)
Tilak Maddy

20

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"

11

您可以使用以下代码获取当前时区

 func getCurrentTimeZone() -> String{

         return TimeZone.current.identifier

  }

  let currentTimeZone = getCurrentTimeZone()
   print(currentTimeZone)

为什么不简单TimeZone.current.identifier
Leo Dabus

@LeoDabus,您也可以使用TimeZone.current.identifier。它们之间没有区别。我只是转换是到其他函数的字符串返回类型
潘卡Jangid

@ Leo Dabus,您是对的。这是我的错 感谢您的发现。
潘卡Jangid

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

名称将类似于“澳大利亚/悉尼”或“欧洲/里斯本”。

既然听起来您可能只关心非洲大陆,那可能就是您所需要的。


5
Swift 3的等效项是TimeZone.current.identifier
Anand

-1

斯威夫特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)"
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.