Yes, Use Joda-Time
Definitely use Joda-Time or the java.time package in Java 8 (inspired by Joda-Time). The old java.util.Date
and java.util.Calendar
classes are notoriously troublesome, confusing, and outmoded.
Also, read the Wikipedia pages on UTC and ISO 8601.
Yes, Pass Date To Joda-Time Constructor
➔ Yes indeed, you can pass a java.util.Date
object to the constructor of a Joda-Time DateTime
object.
The API doc is a bit confusing as this apparently falls into the catch-all version of the constructor taking an java.lang.Object
instance. If that Object is in fact a java.util.Date
, Joda-Time will extract its millisecond-count-since-epoch and use that number as its own.
Time Zone
A DateTime
constructor also assigns a time zone. By default, the JVM’s current default time zone is assigned. I recommend you always pass a desired time zone rather than rely implicitly on the default even if that means calling getDefault
.
Example Code
Here is some example code in Joda-Time 2.5 showing how to pass a java.util.Date to a Joda-Time constructor.
java.util.Date date = new java.util.Date();
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTimeMontreal = new DateTime( date , zone );
DateTime dateTimeUtc = dateTimeMontreal.withZone( DateTimeZone.UTC ); // Adjust to another time zone.
Dump to console.
System.out.println( "date: " + date ); // Misleading output. A j.u.Date is in UTC but its toString method applies JVM’s current default time zone.
System.out.println( "dateTimeMontreal: " + dateTimeMontreal );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run.
date: Sat Oct 18 18:54:55 PDT 2014
dateTimeMontreal: 2014-10-18T21:54:55.740-04:00
dateTimeUtc: 2014-10-19T01:54:55.740Z
As shown in the Question, to go from a DateTime to java.util.Date, call toDate
.
java.util.Date date = dateTimeMontreal.toDate();