I want to convert a java.util.Date
to JodaTime
so as to carry out subtractions between dates. Is there a good concise way to convert from Date
to JodaTime
?
Asked
Active
Viewed 2e+01k times
262

rink.attendant.6
- 44,500
- 61
- 101
- 156

Krt_Malta
- 9,265
- 18
- 53
- 91
2 Answers
502
java.util.Date date = ...
DateTime dateTime = new DateTime(date);
Make sure date
isn't null
, though, otherwise it acts like new DateTime()
- I really don't like that.

skaffman
- 398,947
- 96
- 818
- 769
-
9So basically: `DateTime dateTime = date==null?null:new DateTime(date);` – Joeri Hendrickx Feb 18 '11 at 15:47
-
127+1 for "otherwise it acts like new DateTime() - I really don't like that." – reevesy Apr 27 '12 at 12:10
-
@JoeriHendrickx Old thread but don't you mean DateTime dateTime = date ==null ? new DateTime() : new DateTime(date); ? Just wondering... tx – Babajide Prince May 05 '13 at 23:00
-
1@BabajidePrince No; then you would get the same value as new DateTime(null), which is exactly what we wanted to avoid. The expression is meant to maintain null as null, which is what makes sense in most situations. – Joeri Hendrickx May 07 '13 at 21:35
-
4Be aware that Java Date is TimeZone independent while Joda DateTime has a Chronology. – Cristian Vrabie Jul 26 '13 at 11:58
-
1Yes, a time or two the if null act like new DateTime() is caused me a bit of anoyingness... – buzzsawddog Nov 14 '13 at 17:08
-
2Generally better to specify a time zone rather than rely on implicit default. If you omit a time zone, the JVM's default time zone is assigned to new DateTime object. I suggest this… `DateTime dateTime = new DateTime( date, DateTimeZone.forID( "Europe/Paris" ) );`. Or, for UTC use the constant… `DateTime dateTime = new DateTime( date, DateTimeZone.UTC );` – Basil Bourque Jul 05 '14 at 04:50
-
I just got bitten with the passing null behaviour and remembered seeing this. – Harry Feb 03 '17 at 22:18
15
http://joda-time.sourceforge.net/quickstart.html
Each datetime class provides a variety of constructors. These include the Object constructor. This allows you to construct, for example, DateTime from the following objects:
* Date - a JDK instant
* Calendar - a JDK calendar
* String - in ISO8601 format
* Long - in milliseconds
* any Joda-Time datetime class

Heathen
- 623
- 5
- 13
-
16@skaffman if you wanted to avoid null dates you could use date.getTime() instead. You would be getting a null pointer exception however that may be better than silently failing. – Heathen Feb 18 '11 at 14:49
-
2I wonder why they didn't just overloaded their constructor for those objects. – Pieter De Bie Oct 23 '15 at 09:25
-
2@PieterDeBie - because the system is generic. You can register your own object types to have conversion to or from. – Jules Apr 30 '17 at 01:22