将UNIX /纪元时间转换为h:mm

时间:2017-07-17 21:18:47

标签: java android

我需要什么

我需要将类似“1500322822.816785”的内容转换为“3:45 PM”之类的格式。

我尝试了什么

    public static String fromUnixTimestamp(String timestamp) {

    double itemDouble = Double.parseDouble(timestamp);
    long itemLong = (long) itemDouble;
    Date itemDate = new Date(itemLong);
    String itemDateStr = new SimpleDateFormat("h:mm a").format(itemDate);


    return itemDateStr;
}

会发生什么

当double被转换为long时,它会被舍入(我认为),所以如果它们在几分钟之内就会有相同的时间。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

//i've removed the decimal digits from your number and added the L for long casting
Date itemDate = new Date(1500322822L * 1000);
//or alternatively you can do 
//Date itemDate = new Date((long)1500322822 * 1000);
String text = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a").format(itemDate);
//text is now "17-07-2017 08:20:22 PM"

您需要将UNIX时间乘以x 1000,因为Java java.util.Date类需要毫秒