2017-07-19 39 views
0

當用戶在美國時,爲什麼此代碼在時區返回空白? 在其他國家完美運作。如果在洛杉磯時區爲空

// Get local time zone 
let localTimeZoneAbbreviation = TimeZone.current.abbreviation() ?? "" 
let indexStartOfText = localTimeZoneAbbreviation.index(localTimeZoneAbbreviation.startIndex, offsetBy: 3) // 3 
let timeZone = localTimeZoneAbbreviation.substring(from: indexStartOfText) 
print("TimeZone:",timeZone) 

我需要導致一些格式:

「-7」 洛杉磯

「-4」 紐約

「+2」 漢堡

+0

你爲什麼要解析字符串?使用'TimeZone'的'secondsFromGMT'方法。 – rmaddy

+0

如何從秒中提取我需要的東西並精確到全世界 –

+0

您可以使用DateFormatter並設置'dateFormat =「x」' –

回答

1

縮寫出現爲PDT,沒有任何東西在我的位置。所以,沒有抵消得到。

你可以使用rmaddy所說的秒來獲得偏移量。

let seconds = TimeZone.current.secondsFromGMT() 
let hours = seconds/3600 
let minutes = abs(seconds/60) % 60 
let timezoneDiff = String(format: "%+.1d:%.2d", hours, minutes) 
print(timezoneDiff) 

請務必說明不是確切小時數不同的位置。有些是30分鐘。也可能有其他人。

+0

這是完全正確的,但在這種情況下,服務器只需要整數。我正在考慮檢查值'let check = timeZoneInt> 0? 1:timeZoneInt == 0? 0:-1;'而不是在任何情況下操作任何格式的服務器需求。 –