使用unix时间戳显示正确的日出日落时间。

问题描述 投票:0回答:1

我从DarkSkyApi获得了一个UNIX时间戳,用于显示所选地点的日出& 日落时间,我想把它转换为DateTime格式并显示给用户。我希望时间值是本地的。

例子:用户在意大利,选择 "Tokyo, JP "作为想要获取天气信息的地点。日出& 日落时间值应该被格式化& 显示为当地时间。所以对于东京来说,日出时间应该是4:34 AM & 日落时间是18:36 PM。

以我现在所拥有的东西,我得到了错误的值,如12:17的日出& 2:29的日落。有什么想法,我做错了什么?

P.S. The tmz var是所选地点的时区,所以在这种情况下它应该是 "AsiaTokyo"。下面是我现在正在做的日落时间(日出时间也是如此)。

private fun setViewHolderWeekDaySunsetTime(holder: ViewHolder, sunsetTime: Long, tmz: String) {
    val dt = Instant.ofEpochSecond(sunsetTime).atZone(
        ZoneId.of(tmz)
    )
    val formatted = dt.format(DateTimeFormatter.ofPattern("HH:mm"))
    holder.weekDaySunsetTime.text = formatted
}
android kotlin datetime-format darksky
1个回答
0
投票

听起来像api根据你请求数据的城市返回不同的时区。

所以考虑到这一点,当把时间戳转换为日期时间对象时,你需要做这样的事情。

import java.time.*

val dt = Instant.ofEpochSecond(/*put time value here*/)
                .atZone(/*put time zone here*/)
                .toLocalDateTime() //this will convert it to your system's date time

0
投票

用这个函数找到你想要的每个地方的经纬度时间区。

fun timezonecalculator(latitude:Double,longitude:Double):Double {
    val resultTimeZone = TimezoneMapper.latLngToTimezoneString(latitude, longitude)
    var tz= TimeZone.getTimeZone(resultTimeZone).getDisplayName(
        TimeZone.getTimeZone(resultTimeZone).inDaylightTime(Date()), TimeZone.SHORT)
    if ((tz=="GMT")||(tz=="UTC")||(tz=="WET"))
        tz+="+00:00"
    if ((tz=="CST")||(tz=="MDT"))
        tz+="-06:00"
    if (tz=="AST")
        tz+="-04:00"
    if ((tz=="EST")||(tz=="CDT"))
        tz+="-05:00"
    if (tz=="MST")
        tz+="+05:00"
    if ((tz=="CET")||(tz=="BST"))
        tz+="+01:00"
    if (tz=="EET")
        tz+="+02:00"
    if (tz=="CEST")
    {tz+="+02:00"
        tz=tz.drop(1)}
    if (tz=="PDT")
        tz+="-07:00"
    if (tz=="EDT")
        tz+="-04:00"
    if (tz=="EEST")
    {tz+="+03:00"
    tz=tz.drop(1)}
    if (tz=="WEST")
    {tz+="+01:00"
        tz=tz.drop(1)}
    var sign=tz[3]
    tz=tz.drop(4)
    val minute=tz.drop(3)
    val hour=tz.dropLast(3)
    val min=Integer.parseInt(minute)
    val hou=Integer.parseInt(hour)
    var timezone=hou+(min.toDouble()/60)
    if (sign=='-')
        timezone*=-1
    return timezone
}

而TimeZoneMapper类是 https:/raw.githubusercontent.comdrtimcooperLatLongToTimezonemastersrcmainjavacomskedgoconverterTimezoneMapper.java。

请看这里了解如何使用这个类。https:/github.comdrtimcooperLatLongToTimezone。

你可以这样调用它。timezonecalculator(latitude, longitude)

例如: timezonecalculator(36.2, 59.6)输出: 4.5

© www.soinside.com 2019 - 2024. All rights reserved.