im trying to convert a string(with unix timestamp) to an date with the format ( dd-MM-yyyy)
and this is working partly. The problem im having now is that my date is
I should like to contribute the modern answer.
DateTimeFormatter dateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.forLanguageTag("da"));
String unixTimeStampString = "1427101853";
int dateMulti = Integer.parseInt(unixTimeStampString);
ZonedDateTime dateTime = Instant.ofEpochSecond(dateMulti)
.atZone(ZoneId.of("Africa/Conakry"));
String formattedDate = dateTime.format(dateFormatter);
System.out.println(formattedDate);
The output from this snippet is:
23-03-2015
The output agrees with an online converter (link at the bottom). It tells me your timestamp equals “03/23/2015 @ 9:10am (UTC)” (it also agrees with the date you asked the question). Please substitute your time zone if it didn’t happen to be Africa/Conakry.
The date-time classes that you were using — SimpleDateFormat
, Date
and Calendar
— are long outdated and poorly designed, so I suggest you skip them and use java.time, the modern Java date and time API, instead. A minor one among the many advantages is it accepts seconds since the epoch directly, so you don’t need to convert to milliseconds. While this was no big deal, doing your own time conversions is a bad habit, you get clearer, more convincing and less error-prone code from leaving the conversions to the appropriate library methods.
Yes, java.time
works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.I wrote and ran the above snippet using the backport to make sure it would be compatible with ThreeTenABP.
java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).