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
You are using the wrong format string in the first line:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
mm
is minutes. Use MM
(months) instead.
edit A Unix timestamp is a number of seconds since 01-01-1970 00:00:00 GMT. Java measures time in milliseconds since 01-01-1970 00:00:00 GMT. You need to multiply the Unix timestamp by 1000:
cal.setTimeInMillis(dateMulti * 1000L);
Why you have "dd-mm-yyyy"
in SimpleDateFormat
and "dd-MM-yyyy"
in DateFormat.format
? Use this :
String date = DateFormat.format("dd-mm-yyyy", cal).toString();
If you want minutes, if you want months you have to put MM
like @Jesper said :)
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).I was also facing the same issue when I was using SimpleDateFormat
Here is a method I have made, which is working fine for me.
private String getmDate(long time1) {
java.util.Date time = new java.util.Date((long) time1 * 1000);
String date = DateFormat.format("dd-MMM-yyyy' at 'HH:mm a", time).toString();
return date + "";
}
you can change the date format as you desire.