使用Joda时间获取给定时区的当前墙时间 [英] Using Joda time to get current wall time for a given Time Zone

查看:401
本文介绍了使用Joda时间获取给定时区的当前墙时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要求是简单地获取给定时区的当前待机时间(包括正确的DST调整)。

The requirement is to simply to get the current wall time (including the correct DST adjustment) for a given Time Zone.

似乎有几个问题在这里徘徊,但我似乎无法找到一个直接的答案(在SO,Joda doco或谷歌搜索)获得墙壁时间的低摩擦方式。看起来像给定的输入(当前UTC时间和期望的TZ)我应该能够从Joda Time库链接一些方法来实现我想要的但是在所述示例中似乎希望评估+处理偏移/应用程序代码中的转换 - 如果可能,我想避免这种情况,并根据其可用的静态TZ规则集使用Jodas尽力而为。

There seems to be a few questions in SO hovering around this, but I can't seem to find a straight answer (in SO, Joda doco or googling) with a low friction way of getting the wall time. It seems like with the given inputs (current UTC time and desired TZ) I should be able to chain a couple methods from the Joda Time library to achieve what I want but there seems to be a desire in said examples to evaluate + handle offsets / transitions in application code - I want to avoid this if possible and just use Jodas best effort based on its set of static TZ rules available.

出于这个问题的目的,我们假设我不会使用任何其他第三方服务(基于网络或其他二进制文件),只是JDK提供的服务和JodaTime库。

For the purposes of this question, lets assume that I wont be using any other third party services (network based or other binaries), just what is available from the JDK and JodaTime library.

赞赏任何指针。

更新:
这实际上是我的失误。我根据请求经度计算了计算的 UTC偏移量,而这显然仍然需要区域信息才能获得正确的DST调整。

Update: This was actually a gaffe on my behalf. I had a calculated UTC offset based on the requests longitude, while this works obviously you still need regional information to get the correct DST adjustment..

double aucklandLatitude = 174.730423;
int utcOffset = (int) Math.round((aucklandLatitude * DateTimeConstants.HOURS_PER_DAY) / 360);
System.out.println("Offset: " + utcOffset);

DateTimeZone calculatedDateTimeZone = DateTimeZone.forOffsetHours(utcOffset);
System.out.println("Calculated DTZ: " + calculatedDateTimeZone);
System.out.println("Calculated Date: " + new DateTime(calculatedDateTimeZone));
System.out.println();
DateTimeZone aucklandDateTimeZone = DateTimeZone.forID("Pacific/Auckland");
System.out.println("Auckland DTZ: " +  aucklandDateTimeZone);
System.out.println("Auckland Date: " + new DateTime(aucklandDateTimeZone));

打印

Offset: 12
Calculated DTZ: +12:00
Calculated Date: 2012-02-08T11:20:04.741+12:00

Auckland DTZ: Pacific/Auckland
Auckland Date: 2012-02-08T12:20:04.803+13:00

所以在阳光明媚的奥克兰,新西兰,我们在DST期间+12但+13。

So here in sunny Auckland, NZ we are +12 but +13 in the DST period.

我的不好。谢谢你的答案,让我看到了我的错误。

My bad. Thanks for the answers nonetheless, made me see my mistake.

推荐答案

你看过 DateTime 构造函数:

DateTime(DateTimeZone zone) 

这构造了一个DateTime,表示指定时区的当前时间。

This constructs a DateTime representing the current time in the specified timezone.

这篇关于使用Joda时间获取给定时区的当前墙时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆