How can I convert Date
to DateTime
and vice versa?
E.g.
Date dt = new Date();
Now I want to covert this to DateTime
.
Also
DateTime dtim = new DateTime();
Now I want to convert it to Date.
How can I convert Date
to DateTime
and vice versa?
E.g.
Date dt = new Date();
Now I want to covert this to DateTime
.
Also
DateTime dtim = new DateTime();
Now I want to convert it to Date.
Is this Joda Time
's DateTime
you're talking about? If so, it will be
dateTime.toDate()
I guess you convert it to UTC via Date.getTime(). And after that, use a constructor/setter on the other object.
As skaffman said above
dateTime.toDate()
should do the trick. But keep in mind that if the dateTime object had a different timezone than the user's current timezone, dateTime.toDate() will return the date object in user's timezone. ie
DateTime newDate = new DateTime().toDateTime(DateTimeZone.forID("America/Los_Angeles"));
System.out.println(newDate);
System.out.println(newDate.toDate());
This will print
2017-07-05T14:19:23.294-07:00
Wed Jul 05 15:19:23 MDT 2017
as my system time is in MDT
If you want to convert a DateTime to Date without losing the timezone, convert DateTime to Joda LocalDateTime first.
DateTime dateTimeUtc = new DateTime(); //because my default timezone is UTC
DateTime dateTimeBerlin = dateTimeUtc.withZone(DateTimeZone.forID("Europe/Berlin"));
Date convertedDate = dateTimeBerlin.toLocalDateTime().toDate();
You can easily use the toDate()
function which gets the date time as a java.util.Date
:
Date date = MydateTime.toDate();
Transform to date
:
dateTime.toDate()
Transform to DateTime
:
new DateTime(new Date())