Convert unix/epoch time to formatted date - unexpected date

喜夏-厌秋 提交于 2020-01-15 05:26:28

问题


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


回答1:


1386580621268 is not a unix timestamp i.e. seconds since epoch for 9-12-2013 but milliseconds since epoch. Remove the *1000L or divide the input by 1000.




回答2:


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);
}



回答3:


I solved this way.

public static String Epoch2DateString(String epochSeconds) {
    Date updatedate = new Date(Integer.parseInt(epochSeconds) * 1000L);
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    return format.format(updatedate);
}


来源:https://stackoverflow.com/questions/20654967/convert-unix-epoch-time-to-formatted-date-unexpected-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!