【发布时间】:2019-09-09 21:25:32
【问题描述】:
我正在将本地时区转换为字符串以在屏幕上显示。为此,我使用 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。
提前致谢
【问题讨论】:
-
你能举例说明你的传入格式吗?
-
您需要告诉我们
incomingFormat、outgoingFormat、location、dt、location.timeZone和TimeZone.current的确切值。 -
我正在获取 JSON,并使用以下行:sunrise = "3:22:31 AM";日落 =“下午 5 点 23 分 25 秒”。我使用 CLLocation 中的本地位置,TimeZone.current 由 TimeZoneLocate 库提供
-
你是如何实现这个的?这个函数是作为 String 类型的扩展调用的吗?我试图重新创建它,但“self”不是字符串类型,所以
let dt = dateFormatter.date(from: self)导致错误。 -
是的,它是字符串的扩展