简体   繁体   English

如何将Joda-Time DateTime转换为java.util.Date,反之亦然?

[英]How to convert Joda-Time DateTime to java.util.Date and vice versa?

Is it possible to do that? 有可能吗? If yes, then how do I do the conversion from Joda-Time to Date and vice versa? 如果是,那么如何从Joda-Time转换为Date ,反之亦然?

To convert Java Date to Joda DateTime :- 要将Java Date转换为Joda DateTime : -

Date date = new Date();
DateTime dateTime = new DateTime(date);

And vice versa:- 反之亦然: -

Date dateNew = dateTime.toDate();

With TimeZone , if required:- 使用TimeZone ,如果需要: -

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: 您没有在Joda Time中指定您感兴趣的类型,但是:

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. DateInstant都与时区无关,因此无需在此处指定。

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. LocalDateTime / LocalDate / LocalTime转换为Date (反之亦然)是没有意义的,因为这取决于所应用的时区。

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. 使用DateTime您可以转换 Date而不指定时区,但要从Date转换为DateTime您应指定时区,否则它将使用系统默认时区。 (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: 要从Java Date转换为Joda Date of Date:
To convert from Date to DateTime time zone needed to be specified. 要从Date转换为DateTime时区需要指定。
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转换为Joda Time of Date,您只需将java.util日期和时区传递给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: 要从Joda时间转换为Java日期:
For the reverse case Joda DateTime has a method toDate() which will return the java.util Date. 对于相反的情况,Joda DateTime有一个方法toDate() ,它将返回java.util Date。

DateTime jodaDate = new DateTime();
java.util.Date date = jodaDate.toDate();

For More Details Visit Here 详情请访问此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM