我需要获取时区的缩写。
例如,俄罗斯莫斯科的缩写为MSK
。中欧时间缩写为CET
,东欧夏令时缩写为EEST
,等等。
打开macOS设置时,我可以清楚地看到缩写:
但是,当我尝试在代码中获得缩写时,我只会得到GMT
偏移量:
import UIKit
let date = Date()
let zone = TimeZone(abbreviation: "EEST")
print(zone?.abbreviation(for: Date()))
可选(“ GMT + 3”)
另一方面,当我尝试使用美国时间时,我会得到正确的缩写:
import UIKit
let date = Date()
let zone = TimeZone(abbreviation: "EDT")
print(zone?.abbreviation(for: Date()))
可选(“ EDT”)
如何始终执行TimeZone
来提供缩写而不是GMT偏移量?不管语言环境或其他系统设置,是否还有其他方法可以始终获得缩写?
我的目标是获取与macOS设置相同的字符串。
答案 0 :(得分:0)
我正在玩代码段。希望能帮助您解决问题。
import Foundation
import UIKit
import CoreLocation
public struct LocalTime {
var timeZone: TimeZone?
var dateTime: String
init(timeZone: TimeZone, dateTime: String) {
self.timeZone = timeZone
self.dateTime = dateTime
}
}
class ViewController: UIViewController {
var timeZone: TimeZone?
var localTime: LocalTime?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.getLocalTimeZone(lat: 47.6062, lon: -122.3321, dateTime: "2017-06-10T00:30:00Z")
}
override func viewDidAppear(_ animated: Bool) {
}
func convertToLocalDateFromUTCDate(dateStr: String) -> String {
let utcDateFormatter = DateFormatter()
utcDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let sourceDate = utcDateFormatter.date(from: dateStr)
let localDateFormatter = DateFormatter()
localDateFormatter.timeZone = self.timeZone
localDateFormatter.dateFormat = "dd-MM-yyyy HH:mm:'00'"
guard let date = sourceDate else { return "" }
let localTime = localDateFormatter.string(from: date)
return localTime
}
func getLocalTimeZone(lat: Double, lon: Double, dateTime: String) {
let location = CLLocation(latitude: lat, longitude: lon)
let geoCoder = CLGeocoder()
var dateTimeString: String?
geoCoder.reverseGeocodeLocation(location) { [weak self] (placemarks, err) in
if let placemark = placemarks?[0] {
guard let self = self else { return }
dateTimeString = self.convertToLocalDateFromUTCDate(dateStr: dateTime)
guard let timeZone = placemark.timeZone, let dateTimeString = dateTimeString else { return }
self.localTime = LocalTime(timeZone: timeZone, dateTime: dateTimeString)
debugPrint("?\(self.localTime?.timeZone?.abbreviation())")
debugPrint("?\(self.localTime?.dateTime)")
}
}
}
}
输出:
"?Optional(\"PDT\")"
"?Optional(\"10-06-2017 07:30:00\")"