【发布时间】:2018-11-10 17:21:29
【问题描述】:
我正在制作一个应用程序,它决定了日落和日出。尽管如此,我发现使用用户的本地时间让他们遇到一些困难。因此,我想知道:如何在 Swift 中获取用户的时区?
我在 iPhone 模拟器中加载的测试位置(墨西哥巴亚尔塔港)的坐标如下:
纬度:20.61 经度:-106.23
接下来是我的代码的一部分,用于确定世界上任何位置的日出和日落:
//First we get the sunrise time.
let sunriseDate = Date(timeIntervalSince1970: sunriseValue.doubleValue)
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .medium
formatter.timeZone = NSTimeZone(name: "UTC")! as TimeZone
formatter.dateFormat = "HH:mm:ss"
let sunrise = formatter.string(from: sunriseDate)
print(sunrise)
//Second, we get the sunset time
let sunsetDate = Date(timeIntervalSince1970: sunsetValue.doubleValue)
let sunset = formatter.string(from: sunsetDate)
print(sunset)
这就是我从控制台得到的:
日出:13:08:12 日落:00:21:22
这很明显打印的日出和日落对应于 UTC,但我还没有找到任何直接信息可以帮助我获取用户的当地时间,无论该人在哪里。
基本上你在上面的代码中看到的日出和日落我从一个 API (openweather) 得到它,我从中得到了它们在 unix 时间中的值(我使用这个 link 转换为日期和时间。现在我明白了我有效地获得了正确的日落和日出,但采用 UTC 格式,现在我错过了从 UTC 到当地时间的一步。
所以,总而言之,我得到了:
来自 API:unix 时间中的时间(例如,日出 = 1541855294;日落 = 1541895681;),使用 DateFormatter() 从中提取时间(参见上面的代码),我得到了 UTC 时间(formatter.dateFormat = "HH: mm:ss")。
我希望通过这次修改,问题现在更清楚了。
这就是为什么我想问你是否可以帮我解决这个问题,拜托:)
提前致谢,如有任何误解,我深表歉意!
【问题讨论】:
-
您是否尝试过不设置 formatter.timeZone?然后应该使用用户设置中的时区。
-
顺便说一句 - 如果您确实使用时区,请使用
TimeZone,而不是NSTimeZone。 -
你想用用户的本地时间还是坐标的本地时间来显示时间?对于后者,您需要知道坐标的时区。
-
你好 rmaddy。我想保持简单,所以我只想显示用户的时间(只有时间 HH:mm:ss)@M
-
@JorgeAlbertoFuentesCasillas 然后只需删除设置格式化程序的 timeZone 属性的行就完成了,就像 Martin 在第一条评论中所说的那样。