How to convert DateTime to Date

徘徊边缘 提交于 2019-12-04 15:42:47

问题


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


来源:https://stackoverflow.com/questions/1005596/how-to-convert-datetime-to-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!