[英]How to convert DateTime to Date
How can I convert Date
to DateTime
and vice versa?如何将Date
转换为DateTime
,反之亦然?
Eg例如
Date dt = new Date();
Now I want to covert this to DateTime
.现在我想将其转换为DateTime
。
Also还
DateTime dtim = new DateTime();
Now I want to convert it to Date.现在我想将它转换为日期。
Is this Joda Time
's DateTime
you're talking about?你说的是Joda Time
的DateTime
吗? If so, it will be如果是这样,它将是
dateTime.toDate()
As skaffman said above正如skaffman上面所说
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.但请记住,如果 dateTime object 的时区与用户当前时区不同,dateTime.toDate() 将返回用户时区中的日期 object。 ie 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 2017-07-05T14:19:23.294-07:00
Wed Jul 05 15:19:23 MDT 2017 MDT 2017 年 7 月 5 日星期三 15:19:23
as my system time is in MDT因为我的系统时间在 MDT
I guess you convert it to UTC via Date.getTime().我猜你通过 Date.getTime() 将它转换为 UTC。 And after that, use a constructor/setter on the other object.然后,在另一个 object 上使用构造函数/setter。
Transform to date
:转换date
:
dateTime.toDate()
Transform to DateTime
:转换为DateTime
时间:
new DateTime(new Date())
If you want to convert a DateTime to Date without losing the timezone, convert DateTime to Joda LocalDateTime first.如果要在不丢失时区的情况下将 DateTime 转换为 Date,请先将 DateTime 转换为 Joda LocalDateTime。
DateTime dateTimeUtc = new DateTime(); //because my default timezone is UTC
DateTime dateTimeBerlin = dateTimeUtc.withZone(DateTimeZone.forID("Europe/Berlin"));
Date convertedDate = dateTimeBerlin.toLocalDateTime().toDate();
Easiest way, would be to use the built-in toDate()
method, like:最简单的方法是使用内置的toDate()
方法,例如:
Date dt = new Date();
DateTime datetime = New DateTime(dt);
Date result = dateTime.toDate();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.