Unix 纪元时间到 Java 日期对象 [英] Unix epoch time to Java Date object
问题描述
我有一个包含 UNIX Epoch time 的字符串,我需要将其转换为Java 日期对象.
I have a string containing the UNIX Epoch time, and I need to convert it to a Java Date object.
String date = "1081157732";
DateFormat df = new SimpleDateFormat(""); // This line
try {
Date expiry = df.parse(date);
} catch (ParseException ex) {
ex.getStackTrace();
}
标记的线是我遇到问题的地方.我不知道 SimpleDateFormat() 的参数应该是什么,或者即使我应该使用 SimpleDateFormat().
The marked line is where I'm having trouble. I can't work out what the argument to SimpleDateFormat() should be, or even if I should be using SimpleDateFormat().
推荐答案
怎么样:
Date expiry = new Date(Long.parseLong(date));
根据 rde6173 的回答并仔细查看问题中指定的输入,1081157732" 似乎是基于秒的纪元值,因此您希望将来自 parseLong() 的 long 乘以 1000 以转换为毫秒,这是 Java 的 Date 构造函数所使用的,因此:
as per rde6173's answer and taking a closer look at the input specified in the question , "1081157732" appears to be a seconds-based epoch value so you'd want to multiply the long from parseLong() by 1000 to convert to milliseconds, which is what Java's Date constructor uses, so:
Date expiry = new Date(Long.parseLong(date) * 1000);
这篇关于Unix 纪元时间到 Java 日期对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!