如何获取设备时区?
How to Get device timezone?
我使用以下代码获取设备时区
func getCurrentTimeZone() -> String{
return TimeZone.current.identifier
}
let currentTimeZone = getCurrentTimeZone()
print(currentTimeZone)
它给出了位置,例如“Asia/Dhaka”,但我想获得“+02:00 或 -04:30”格式。
如何将值转换为所需格式?
所需的格式似乎是 ISO 8601 format,在这种情况下,您可以使用 ISO8601DateFormatter
:
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withTimeZone, .withColonSeparatorInTimeZone]
dateFormatter.timeZone = TimeZone.current
let formattedTimezone = dateFormatter.string(from: Date())
请注意,我在最后一行使用了 Date()
。这将输出当前时刻与 GMT 的时区偏移量。将其替换为您选择的 Date
,以获取该时区与 GMT 的偏移量 that Date
。
我使用以下代码获取设备时区
func getCurrentTimeZone() -> String{
return TimeZone.current.identifier
}
let currentTimeZone = getCurrentTimeZone()
print(currentTimeZone)
它给出了位置,例如“Asia/Dhaka”,但我想获得“+02:00 或 -04:30”格式。 如何将值转换为所需格式?
所需的格式似乎是 ISO 8601 format,在这种情况下,您可以使用 ISO8601DateFormatter
:
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withTimeZone, .withColonSeparatorInTimeZone]
dateFormatter.timeZone = TimeZone.current
let formattedTimezone = dateFormatter.string(from: Date())
请注意,我在最后一行使用了 Date()
。这将输出当前时刻与 GMT 的时区偏移量。将其替换为您选择的 Date
,以获取该时区与 GMT 的偏移量 that Date
。