Joda-time 使用

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"));
where  DateTimeZone.forID("Europe/London") returns the timezone value for London. The resulting value  dtLondon has the same absolute millisecond time, but a different set of field values.

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