Kla*_*kao 5 android date kotlin
我正在开发一个简单的天气应用程序,并尝试以“K:mm a”格式显示时间(例如上午 6:30)。我正在获取用户搜索的指定地点(例如纽约市)的 Unix、UTC 时间戳。时间戳看起来类似于 1624836905,时区偏移量类似于 -14400。我有一个函数将两者相加,将其转换为毫秒,并应以指定的格式返回时间。函数如下:
fun dateTime(time: Int, zone: Int, format: String = "EEE, MMMM d K:mm a"): String {
return try {
val sdf = SimpleDateFormat(format)
val netDate = Date((time.plus(zone)).toLong() * 1000)
sdf.timeZone = TimeZone.getTimeZone("UTC")
sdf.format(netDate)
} catch (e: Exception) {
e.toString()
}
}
Run Code Online (Sandbox Code Playgroud)
我称之为:
sunriseTextView.text = dateTime(result2.lookup<Int>("daily.sunrise")[0], timeZone, "K:mm a")
sunsetTextView.text = dateTime(result2.lookup<Int>("current.sunset")[0], timeZone, "K:mm a")
Run Code Online (Sandbox Code Playgroud)
预期输出是日出/日落时间,例如上午 6:01 和晚上 9:05。我还在指定位置渲染了同样从 API 获得的当前时间。如下:
dateView.text = dateTime(result2.lookup<Int>("current.dt")[0], timeZone)
Run Code Online (Sandbox Code Playgroud)
它以“EEE, MMMM d K:mm a”的格式输出该地点的当前日期和时间(例如,Mon June 28 8:23 AM)。
当前时间始终是正确的,但是日出和日落时间存在问题。例如,如果我输入 NYC,日出时间为晚上 7:35,日落时间为上午 10:39。另一方面,东京的日出和日落在凌晨 4:27 和晚上 7:00 看起来是正确的。
显然我错过了一些东西,因为我知道 API 数据是正确的。我正在寻找任何建议,但是,我希望有一个没有 API 限制的建议,例如需要 API 26 的 kotlinx-datetime。
我在Python中有一个类似的函数,如下所示:
def time(self, unix_time, time_zone):
date = datetime.utcfromtimestamp(unix_time + time_zone)
return (datetime.strftime(date, '%I:%M %p'))
Run Code Online (Sandbox Code Playgroud)
我称之为:
WeatherApp.time_zone = self.weather_results['timezone_offset']
print(self.time_date(self.weather_results['current']['dt'], self.time_zone))
print('Sunrise: ' + self.time(self.weather_results['current']['sunrise'], self.time_zone))
print('Sunset: ' + self.time(self.weather_results['current']['sunset'], self.time_zone))
Run Code Online (Sandbox Code Playgroud)
我试图在 Kotlin 中得到相同的结果。然而,比较输出如下:
Location: Tokyo, Japan
Current time and date: Tue, June 29 06:53 PM (same in Python and Kotlin from Asia/Tokyo, 1624960598 1624961970
32400)
Sunrise: 04:27 AM (as outputted in Python from 32400, 1624908462)
Sunset: 07:00 PM (as outputted in Python from 32400, 1624960847)
Sunrise: 4:27 AM (as outputted in Kotlin from Asia/Tokyo, 1624908467)
Sunset: 7:00 PM (as outputted in Kotlin from Asia/Tokyo, 1624960846)
---
Location: New York, United States
Current time and date: Tue, June 29 6:02 AM (same in Python and Kotlin from America/New_York, 1624960973)
Sunrise: 05:27 AM (as outputted in Python from -14400, 1624958860)
Sunset: 08:31 PM (as outputted in Python from -14400, 1625013070)
Sunrise: 7:35 PM (as outputted in Kotlin from America/New_York, 1624923330)
Sunset: 10:39 AM (as outputted in Kotlin from America/New_York, 1624977548)
Run Code Online (Sandbox Code Playgroud)
比较时间戳可以看出,由于某种原因,从 API 获取的数据有所不同。我目前通过使用不同的 API 解决了这个问题。我使用的是 OpenWeather 的 One Call API。我想不出发生这种情况的原因,但是,通过从不同的 API 获取时间戳,问题不再存在。
| 归档时间: |
|
| 查看次数: |
2424 次 |
| 最近记录: |