Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

android - Showing correct sunrise/sunset times using unix timestamp

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 the user. I want the time values to be local.

Example case : The user is in Italy and selects "Tokyo, JP" as the desired location to fetch weather info for. The sunrise & sunset time values should be formatted & shown as local times. So for Tokyo, sunrise should be something around 4:34 AM & 18:36 PM for sunset.

With what i have right now, i'm getting wrong values such as 12:17 for sunrise & 2:29 for sunset. Any ideas on what i'm doing wrong here?

P.S. The tmz var is the timezone of the selected location , so in this case it would be "Asia/Tokyo". Here's what i'm doing right now for the sunset time (same for the sunrise time):

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...