I am getting UTC timestamp from database which is I am setting into a JodaTime DateTime
instance
DateTime dt = new DateTime(timestamp.getTime())
None of the given answers actually explained the problem. The real problem is the initial assumptions were incorrect. The timestamp from the database was created using the local JVM timezone Asia/Kolkata
and not UTC. This is the default behavior with JDBC which is why it's still recommended to set your JVM timezone to UTC.
If the timestamp from the database were in fact:
2013-09-25 11:27:34 AM UTC
Or in ISO-8601 format:
2013-09-25T11:27:34Z // The trailing 'Z' means UTC
Then using the new DateTime(timestamp, DateTimeZone.UTC)
constructor works fine. See for yourself:
Timestamp timestamp = new Timestamp(1380108454000L);
DateTime dt = new DateTime(timestamp.getTime(), DateTimeZone.UTC);
System.out.println(dt); // => 2013-09-25T11:27:34.000Z
If you're wondering how I got 1380108454000L
, I simply used the Joda parsing classes:
ISODateTimeFormat.dateTimeParser().parseMillis("2013-09-25T11:27:34Z")
Alternatively there are websites online where you can enter a date, time, and timezone and it returns the epoch value in milliseconds or vice versa. It's sometimes good as a sanity check.
// https://www.epochconverter.com
Input: 1380108454000 Click: "Timestamp to Human Date"
Assuming that this timestamp is in milliseconds:
GMT: Wednesday, September 25, 2013 11:27:34 AM
Also, keep in mind the java.sql.Timestamp
class roughly correlates to the Joda/Java 8+ Instant
class. Sometimes it's easier to convert between equivalent classes to spot bugs like this earlier.