Convert unix/epoch time to formatted date - unexpected date

DevC picture DevC · Dec 18, 2013 · Viewed 9.5k times · Source

Im trying to convert a timestamp to a human readable date and time. I tried:

String dateSt = 1386580621268;
Log.i("*****", "date st is = "+dateSt);
long unixSeconds = Long.parseLong(dateSt);
Log.i("*******", "unix seconds is = "+unixSeconds);
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); // the format of your date
String formattedDate = sdf.format(date);
System.out.println(formattedDate);

The expected result is to be 09-12-2013, however i get 28-12-45908. The above example can be found at: Convert Unix timestamp to date java, answer by David Hofmann

Answer

No_Rulz picture No_Rulz · Dec 18, 2013

Try this,

public static String Epoch2DateString(long epochSeconds, String formatString) {
    Date updatedate = new Date(epochSeconds * 1000);
    SimpleDateFormat format = new SimpleDateFormat(formatString);
    return format.format(updatedate);
}