Unix epoch time to Java Date object

2019-01-01 05:16发布

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

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().

7条回答
明月照影归
2楼-- · 2019-01-01 06:02

To convert seconds time stamp to millisecond time stamp. You could use the TimeUnit API and neat like this.

long milliSecondTimeStamp = MILLISECONDS.convert(secondsTimeStamp, SECONDS)

查看更多
无色无味的生活
3楼-- · 2019-01-01 06:07

Better yet, use JodaTime. Much easier to parse strings and into strings. Is thread safe as well. Worth the time it will take you to implement it.

查看更多
一个人的天荒地老
4楼-- · 2019-01-01 06:11

Epoch is the number of seconds since Jan 1, 1970..

So:

String epochString = "1081157732";
long epoch = Long.parseLong( epochString );
Date expiry = new Date( epoch * 1000 );

For more information: http://www.epochconverter.com/

查看更多
无与为乐者.
5楼-- · 2019-01-01 06:11

Hum.... if I am not mistaken, the UNIX Epoch time is actually the same thing as

System.currentTimeMillis()

So writing

try {
    Date expiry = new Date(Long.parseLong(date));
}
catch(NumberFormatException e) {
    // ...
}

should work (and be much faster that date parsing)

查看更多
深知你不懂我心
6楼-- · 2019-01-01 06:16

How about just:

Date expiry = new Date(Long.parseLong(date));

EDIT: 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);
查看更多
浅入江南
7楼-- · 2019-01-01 06:20
long timestamp = Long.parseLong(date)
Date expiry = new Date(timestamp * 1000)
查看更多
登录 后发表回答