开发者

Timezone conversion in java

开发者 https://www.devze.com 2023-03-11 09:57 出处:网络
I am implementing the following method- DateTime getDateTime(Date srcDate, String destTimeZone) { } As the input is of Date object, I can safely assume the timezone of it as \"UTC\". I have to conv

I am implementing the following method-

DateTime getDateTime(Date srcDate, String destTimeZone) {
}

As the input is of Date object, I can safely assume the timezone of it as "UTC". I have to convert it to destTimeZone and return DateTim开发者_如何学Goe object.

Any pointers in an efficient way to solve this?


Such a method is not really hard to implement with Joda Time:

public DateTime getDateTime( Date srcDate, String destTimeZone )
{
    return new DateTime( srcDate, DateTimeZone.forID( destTimeZone) );
}

The standard Java way would be:

Calendar cal = Calendar.getInstance( TimeZone.getTimeZone( destTimeZone ) );
cal.setTimeInMillis( srcDate.getTime() );
// now you have a Calendar object with time zone set


DateTime getDateTime(Date srcDate, String destTimeZone) {

    return new DateTime(new Date(srcDate.getTime() + 
                   TimeZone.getTimeZone(destTimeZone).getRawOffset()));

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号