Showing correct sunrise/sunset times using unix timestamp

后端 未结 2 1729
不知归路
不知归路 2020-12-07 05:46

I\'m getting a UNIX timestamp from DarkSkyApi for the sunrise & sunset times for the selected location and i want to convert it to a DateTime format and display it to th

相关标签:
2条回答
  • 2020-12-07 06:34

    Use this function to find timezone of every place you want with its latitude and longitude:

    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
    }
    

    And TimeZoneMapper class is https://raw.githubusercontent.com/drtimcooper/LatLongToTimezone/master/src/main/java/com/skedgo/converter/TimezoneMapper.java

    See here to know how to use this class: https://github.com/drtimcooper/LatLongToTimezone

    You invoke it this way: timezonecalculator(latitude, longitude)

    Example: timezonecalculator(36.2, 59.6) Output: 4.5

    0 讨论(0)
  • 2020-12-07 06:46

    it sounds like the api is returning different time zones depending on what city you request data

    So taking that into consideration, when converting the timestamp to a datetime object, you need to do something like this:

    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 讨论(0)
提交回复
热议问题