Is it possible to do that? If yes, then how do I do the conversion from Joda-Time to Date and vice versa?
To convert Java Date
to Joda DateTime
:-
Date date = new Date();
DateTime dateTime = new DateTime(date);
And vice versa:-
Date dateNew = dateTime.toDate();
With TimeZone
, if required:-
DateTime dateTimeNew = new DateTime(date.getTime(), timeZone);
Date dateTimeZone = dateTime.toDateTimeAtStartOfDay(timeZone).toDate();
You haven't specified which type within Joda Time you're interested in, but:
Instant instant = ...;
Date date = instant.toDate();
instant = new Instant(date);
// Or...
instant = new Instant(date.getTime());
Neither Date
nor Instant
are related to time zones, so there's no need to specify one here.
It doesn't make sense to convert from LocalDateTime
/ LocalDate
/ LocalTime
to Date
(or vice versa) as that would depend on the time zone being applied.
With DateTime
you can convert to a Date
without specifying the time zone, but to convert from Date
to DateTime
you should specify the time zone, or it will use the system default time zone. (If you really want that, I'd specify it explicitly to make it clear that it's a deliberate choice.)
For example:
DateTimeZone zone = DateTimeZone.forID("Europe/London");
Date date = ...;
DateTime dateTime = new DateTime(date.getTime(), zone);
To Convert from Java Date to Joda Time of Date:
To convert from Date to DateTime time zone needed to be specified.
To convert from java.util Date to Joda Time of Date you just need to pass the java.util Date and time zone to the constructor of Joda Time of Date.
java.util.Date date = new java.util.Date(System.currentTimeMillis());
DateTimeZone dtz = DateTimeZone.getDefault();// Gets the default time zone.
DateTime dateTime = new DateTime(date.getTime(), dtz);
To Convert from Joda Time of Date to Java Date:
For the reverse case Joda DateTime has a method toDate()
which will return the java.util Date.
DateTime jodaDate = new DateTime();
java.util.Date date = jodaDate.toDate();
For More Details Visit Here
来源:https://stackoverflow.com/questions/15333320/how-to-convert-joda-time-datetime-to-java-util-date-and-vice-versa