How to convert DateTime to Date

2020-06-07 05:39发布

问题:

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.

回答1:

Is this Joda Time's DateTime you're talking about? If so, it will be

dateTime.toDate()


回答2:

I guess you convert it to UTC via Date.getTime(). And after that, use a constructor/setter on the other object.



回答3:

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



回答4:

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();


回答5:

You can easily use the toDate() function which gets the date time as a java.util.Date:

Date date = MydateTime.toDate();


回答6:

Transform to date:

dateTime.toDate()

Transform to DateTime:

new DateTime(new Date())