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")));
It worked! But, is there any way to "force" to use milliseconds instead of seconds through the
DateFormat
orCalendar
?– rsicarelli
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);
– Math