Java: Date from unix timestamp

I need to convert a unix timestamp to a date object.
I tried this:

java.util.Date time = new java.util.Date(timeStamp);

Timestamp value is: 1280512800

The Date should be "2010/07/30 - 22:30:00" (as I get it by PHP) but instead I get Thu Jan 15 23:11:56 IRST 1970 .

How should it be done?


For 1280512800 , multiply by 1000, since java is expecting milliseconds:

java.util.Date time=new java.util.Date((long)timeStamp*1000);

If you already had milliseconds, then just new java.util.Date((long)timeStamp);

From the documentation:

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.


这是正确的方法:

Date date = new Date ();
date.setTime((long)unix_time*1000);

java.time

Java 8 introduced a new API for working with dates and times: the java.time package.

With java.time you can use:

Date date = Date.from( Instant.ofEpochSecond( timeStamp ) );

An Instant represents a timestamp in Java 8. With the static Date.from() method you can convert an Instant to a java.util.Date instance.

链接地址: http://www.djcxy.com/p/6292.html

上一篇: 将日期值转换为

下一篇: Java:来自unix时间戳的日期