我正在将本地时区转换为字符串以在屏幕上显示它。为此,我使用TimeZoneLocate库。问题:由于没有实现夏令时,我得到的日期结果比它少一个小时。
我从sunrise-sunset.org获取JSON,并使用以下行:sunrise =“3:22:31 AM”;日落=“下午5:23:25”。
我考虑过使用isDaylightSavingTime()
函数与if
语句,但我无法弄清楚这一小时的添加位置。
这是魔术发生的功能:
func UTCToLocal(incomingFormat: String, outgoingFormat: String, location: CLLocation?) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = incomingFormat
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dt = dateFormatter.date(from: self)
let timeZone = location?.timeZone ?? TimeZone.current
dateFormatter.timeZone = timeZone
dateFormatter.dateFormat = outgoingFormat
return dateFormatter.string(from: dt ?? Date())
}
我使用来自CLLocation的本地“位置”,TimeZone.current由TimeZoneLocate库提供。
这是我在代码中使用它的方式:
func parce(json: Data, location: CLLocation) {
let decoder = JSONDecoder()
if let sunriseData = try? decoder.decode(Results.self, from: json) {
self.sunriseLbl.text = sunriseData.results?.sunrise.UTCToLocal(incomingFormat: "h:mm:ss a",
outgoingFormat: "HH:mm",
location: location)
sunriseLbl默认从JSON打印当前位置的日出数据,以及GooglePlaces为任何地点打印日出数据。但是,在这两者中,我都错了日期。
另外,这里是我在GitHub上的项目的链接,如果它可以帮助你帮助我:https://github.com/ArtemBurdak/Sunrise-Sunset。
提前致谢
我注意到一个有趣的事情:TimeZone.current
正在返回正确的时区,但location?.timeZone
没有返回正确的时区。如果有办法实现TimeZone.current,即应用程序将始终使用用户的当前位置,那么我建议使用它。但是,如果用户可以输入自定义位置,则需要针对location?.timeZone
返回的明显错误时区获取解决方法。
我的解决方法如下。请注意,我们通过更改.secondsFromGMT()
属性手动调整所需时区的位置。这就是我调整代码的方式,它为我的个人位置返回了正确的时区。
extension String {
func UTCToLocal(incomingFormat: String, outgoingFormat: String, location: CLLocation?) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = incomingFormat
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dt = dateFormatter.date(from: self)
var timeZone = location?.timeZone ?? TimeZone.current
if timeZone.isDaylightSavingTime() {
timeZone = TimeZone(secondsFromGMT: timeZone.secondsFromGMT() - 7200)!
}
dateFormatter.timeZone = timeZone
dateFormatter.dateFormat = outgoingFormat
let output = dateFormatter.string(from: dt ?? Date())
return output
}
}
注意:时区非常复杂,并且从一个地方到一个地方的当前时间会发生变化。仅仅因为此解决方法适用于当前当前位置,并不意味着此解决方法始终有效。但是,您可以根据需要查看返回的timeZone.isDaylightSavingTime()
值以及当前位置以通过timeZone = TimeZone(secondsFromGMT: timeZone.secondsFromGMT() - x
创建新时区。这是你可以实现的方式
“我考虑过使用带有if语句的函数isDaylightSavingTime(),但我无法弄清楚这一小时的添加位置。”
你有这个想法。
编辑:为了记录,我使用的时区是CST,或芝加哥时间。我写这段代码的日期是2019年4月19日。