Formatting String with Dateformat using a Timezone is not working

Asked

Viewed 917 times

3

In my web service, there is an endpoint that returns a timestamp to me 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 this date is converted into some converter she gets like:

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

Does anyone have any idea why?

3 answers

5


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

Sat Jan 17 1970 11:51:53 GMT-0200 (Brazilian daylight saving time)

To arrive at the date you want to add 000 at the end of the amount you had used to see that the date is exactly equal to the output of the site you used as a test, only on the site is not considering the UTC, so it is giving three hours difference. Thus:

formatDate(1432313391000L, "UTC");

Exit:

22/05/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
}
  • It worked! But, is there any way to "force" to use milliseconds instead of seconds through the DateFormat or Calendar?

  • 1

    No, as you can see here: http://docs.oracle.com/javase/7/docs/api/java/util/Date.html#Date(long) it waits for input in milliseconds, you can do a multiplication by 1000 before passing the value, if you already receive the number in seconds, so: return f.format(date * 1000);

0

From Java 8 (or, if on Android, from the Level 26 API (required minSdkVersion >= 26, it is not enough to have compileSdkVersion >= 26)), you can use the API java.time.

In this case, you do not need to multiply the value of the timestamp by 1000, simply passing it directly to a java.time.Instant, and then converting it to a java.time.ZonedDateTime (which corresponds to a date and time in a specific Timezone), and finally formatting. You will need these import's:

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

And the code goes like this:

public static String formatDate(long date, String timeZone) {
    DateTimeFormatter formatter = DateTimeFormatter
        // usa os formatos localizados
        .ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.MEDIUM);
    return Instant
        // converte os segundos para um Instant
        .ofEpochSecond(date)
        // converte para o timezone
        .atZone(ZoneId.of(timeZone))
        // formata
        .format(formatter);
}

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

By default, the DateTimeFormatter already uses the default locale JVM, so you don’t have to Locale.getDefault(). But if you want to change to one locale other than default, just do:

DateTimeFormatter formatter = DateTimeFormatter
    // usa os formatos localizados
    .ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.MEDIUM);
    // seta o locale
    .withLocale(new Locale("pt", "BR")));

0

You can use the class Calendar 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

  • The UTC date comes from my web service, not the device date

  • You pass the date on setTimeInMillis

  • The bug continues!

  • No need to set Timezone, I edited the answer.

  • Keep returning the same value to me :/

  • What value is coming from the server?

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.