java joda 获取utc时间,使用Joda-Time获取给定日期和时区的UTC偏移量

I have dates in the format 20Jan2013, 08Aug2012 etc, with their own specific timezones. So for example, 20Jan2013 might have a timezone ID of Australia/Melbourne, and 08Aug2012 might have an ID of Europe/London. What I want to do is, based on these timezones and the dates, calculate the UTC offset for that timezone on the given date. I've come up with this so far:

DateTimeFormatter dtf = DateTimeFormat.forPattern("ZZ");

DateTimeFormatter dtf1 = DateTimeFormat.forPattern("ddMMMYYYY");

DateTimeZone zone = DateTimeZone.forID("Australia/Melbourne");

DateTime thisDate = dtf1.parseDateTime("30Jul2013");

System.out.println("\nZone: " + thisDate.withZone(zone));

This gives me the output:

Zone: 2013-07-30T00:00:00.000+10:00

This is correct, but I would like to extract just the UTC offset from this, which in this case is +10:00. I've looked for ways to do this but can't find anything. Is there any way I can do this? The only option I see is to convert the output to a String and use the substring method to get the UTC offset.

The above code does take DST (Daylight Saving Time) into account. So for example if I had:

DateTime thisDate = dtf1.parseDateTime("30Jan2013");

The output would be: 2013-01-30T00:00:00.000+11:00

(+11:00 at the end instead of +10:00)

So basically all I need to do is find a way to extract +11:00 from 2013-07-30T00:00:00.000+11:00. Please help!

解决方案

Simple Method for Obtaining Timezone Name and Offset in Hours

public static String getCurrentTimeZoneOffset() {

DateTimeZone tz = DateTimeZone.getDefault();

Long instant = DateTime.now().getMillis();

String name = tz.getName(instant);

long offsetInMilliseconds = tz.getOffset(instant);

long hours = TimeUnit.MILLISECONDS.toHours( offsetInMilliseconds );

String offset = Long.toString( hours );

return name + " (" + offset + " Hours)";

// Example: "Mountain Standard Time (-7 Hours)"

}

Couple caveats:

This gets the default DateTimeZone from JodaTime. You can modify it to accept a specific DateTimeZone that is passed into the method.

This returns it in a format like "Mountain Standard Time (-7 Hours)" but you can format it as you see fit quite easily.

Hope that helps.

JP

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值