Java: Date from unix timestamp

2018-12-31 09:59发布

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?

8条回答
十年一品温如言
2楼-- · 2018-12-31 10:30

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.

查看更多
初与友歌
3楼-- · 2018-12-31 10:37

Date's constructor expects the timeStamp value to be in milliseconds. Multiply your timestamp's value with 1000, then pass is to the constructor.

查看更多
有味是清欢
4楼-- · 2018-12-31 10:38

Looks like Calendar is the new way to go:

Calendar mydate = Calendar.getInstance();
mydate.setTimeInMillis(timestamp*1000);
out.println(mydate.get(Calendar.DAY_OF_MONTH)+"."+mydate.get(Calendar.MONTH)+"."+mydate.get(Calendar.YEAR));

The last line is just an example how to use it, this one would print eg "14.06.2012".

If you have used System.currentTimeMillis() to save the Timestamp you don't need the "*1000" part.

If you have the timestamp in a string you need to parse it first as a long: Long.parseLong(timestamp).

https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

查看更多
步步皆殇っ
5楼-- · 2018-12-31 10:39

If you are converting a timestamp value on a different machine, you should also check the timezone of that machine. For example;

The above decriptions will result different Date values, if you run with EST or UTC timezones.

To set the timezone; aka to UTC, you can simply rewrite;

    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    java.util.Date time= new java.util.Date((Long.parseLong(timestamp)*1000));
查看更多
伤终究还是伤i
6楼-- · 2018-12-31 10:40
Date d = new Date(i * 1000 + TimeZone.getDefault().getRawOffset());
查看更多
墨雨无痕
7楼-- · 2018-12-31 10:46

This is the right way:

Date date = new Date ();
date.setTime((long)unix_time*1000);
查看更多
登录 后发表回答