简体   繁体   中英

Why do I keep getting the wrong date/time when converting from a UTC timestamp?

I am trying to make a weather forecast app, and I am given a UTC timestamp from the api: OpenWeatherMap. I convert it into a date by creating a Date object. For example, for the UTC time stamp 1589220000, the time in UTC is May 11, 6 PM. I do this conversion, and I always get May 11, 2 PM. Coincidentally, I do live in a place where the time is 4 hours behind UTC, but when I tested my app using fake gps location changers, I still got May 11, 2PM. This shows that Android is not creating a calendar based on my current location, because Dubai's time zone is not 4 hours behind as an example.

Heres my code:

public String convertDate(long unixTimeStamp) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat("EEEE, MMM d, h:mm aaa");
        Date date = new Date(unixTimeStamp*1000 );
        String nowDate = dateFormat.format(date);

        return nowDate;
    }

Do yourself a Favor and use java.time.* and not Date / SimpleDateFormat .

If you cannot use API 26/Gradle 4.x or above (and therefore have access to Java 8), then use, until you can, https://www.threeten.org/threetenbp/ which you can use on Android via Jake Wharton's adaptation: https://github.com/JakeWharton/ThreeTenABP

To convert an instant of time since epoch you do:

    val instant = Instant.ofEpochMilli(milliseconds)

    val result = instant.atOffset(ZoneOffset.UTC).toLocalDateTime() //for example

There are plenty of methods to play around with.

Don't forget to Initialize the library for the TimeZone databases to be loaded. In your Application class, add this to onCreate() :

    AndroidThreeTen.init(this)

To format your date, you can continue with the "result" above:

val result = ...
result.format(DateTimeFormatter...)

There are plenty of DateTimeFormatter helper functions, read the documentation, it's quite easy to use.

One of them is ofPattern(...) :

DateTimeFormatter
   .ofPattern("EEEE, MMM d, h:mm aaa")
   .withLocale(Locale.US) // you can use systemDefault or chose another

The sky, is the limit.

You don't set the time zone on the SimpleDateFormat , so you will get the JVM's default time zone:

dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM