JDK Interoperability
The DateTime class has a constructor which takes an Object as input. In particular this constructor can be passed a JDK Date, JDK Calendar or JDK GregorianCalendar (It also accepts an ISO8601 formatted String, or Long object representing milliseconds). This is one half of the interoperability with the JDK. The other half of interoperability with JDK is provided by DateTime methods which return JDK objects.
Thus inter-conversion between Joda DateTime and JDK Date can be performed as follows
// from Joda to JDK
DateTime dt = new DateTime();
Date jdkDate = dt.toDate();
// from JDK to Joda
dt = new DateTime(jdkDate);
Similarly, for JDK Calendar:
// from Joda to JDK
DateTime dt = new DateTime();
Calendar jdkCal = dt.toCalendar(Locale.CHINESE);
// from JDK to Joda
dt = new DateTime(jdkCal);
and JDK GregorianCalendar:
// from Joda to JDK
DateTime dt = new DateTime();
GregorianCalendar jdkGCal = dt.toGregorianCalendar();
// from JDK to Joda
dt = new DateTime(jdkGCal);
Changing TimeZone
DateTime comes with support for a couple of common timezone calculations. For instance, if you want to get the local time in London at this very moment, you would do the following
// get current moment in default time zone
DateTime dt = new DateTime();
// translate to London local time
DateTime dtLondon = dt.withZone(DateTimeZone.forID("Europe/London"));
There is also support for the reverse operation, i.e. to get the datetime (absolute millisecond) corresponding to the moment when London has the same local time as exists in the default time zone now. This is done as follows
// get current moment in default time zone
DateTime dt = new DateTime();
// find the moment when London will have / had the same time
dtLondonSameTime = dt.withZoneRetainFields(DateTimeZone.forID("Europe/London"));
A set of all TimeZone ID strings (such as "Europe/London") may be obtained by calling DateTimeZone.getAvailableIDs(). A full list of available time zones is provided here.
本文介绍了如何在Joda时间和日期类与JDK日期类之间进行互操作,包括从Joda到JDK的日期时间转换,以及如何根据时区需求调整日期时间。
177

被折叠的 条评论
为什么被折叠?



