Search code examples
javaandroidandroid-studiodateutc

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;
    }

Solution

  • 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