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.

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值