Formatting String with DateFormat using a TimeZone is not working

2

In my web service, there is an endpoint that returns me a timestamp in UTC and I have a method that generates a date formatted from this timestamp:

formatDate(1432313391, "UTC");

public String formatDate(long date, String timeZone) 
{
    //Neste caso, o Locale está como ENGLISH (default do aparelho)
    DateFormat f = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM, Locale.getDefault());
    f.setTimeZone(TimeZone.getTimeZone(timeZone));
    return f.format(date);
}

But for some reason this method is returning me to the following String:

  

Jan 17, 1970 1:51:53 PM

If you convert this date into some converter it looks like:

  

5/22/2015, 1:49:51 PM

Anyone have an idea why?

    
asked by anonymous 22.05.2015 / 19:11

2 answers

4

The converter you are using is not considering the time in milliseconds, but in seconds. Using 1432313391 in this other converter the output for your input gives the same result than the Java code:

  

Sat Jan 17 1970 11:51:53 GMT-0200 (Brazilian Daylight Time)

To get to the date you want to add 000 to the end of the value you had used to see that the date is exactly the same as the output of the site you used as a test, but the site is not considering UTC, so it's giving you three hours of difference. So:

formatDate(1432313391000L, "UTC");

Output:

  

05/22/2015 16:49:51

If you already receive the variable with the number in seconds you can multiply by 1000 within the method that formats your String. Example:

public static void main(String[] args) {
    System.out.println(formatDate(1432313391, "UTC"));
}

public static String formatDate(long date, String timeZone) {
    //Neste caso, o Locale está como ENGLISH (default do aparelho)
    DateFormat f = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.getDefault());
    f.setTimeZone(TimeZone.getTimeZone(timeZone));
    return f.format(date * 1000); //transforma de segundos para milisegundos
}
    
22.05.2015 / 19:45
0

You can use the Calendar class as follows:

public String formatDate(long date, String timeZone) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(date);
    DateFormat f = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,   DateFormat.MEDIUM, Locale.getDefault());
    return f.format(calendar.getTime());
}
  

// May 22, 2015 1:36:59 PM

    
22.05.2015 / 19:22