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:If you already had milliseconds, then just
new java.util.Date((long)timeStamp);
From the documentation:
Date's constructor expects the timeStamp value to be in milliseconds. Multiply your timestamp's value with 1000, then pass is to the constructor.
Looks like Calendar is the new way to go:
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
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;
This is the right way: