使用Joda时间获取给定时区的当前墙时间

mar*_*ers 14 java timezone jodatime

要求是简单地获得给定时区的当前墙壁时间(包括正确的DST调整).

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

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

任何指针赞赏.

更新: 这实际上是代表我的失误.我根据请求经度得到了一个计算的 UTC偏移量,而这显然你需要区域信息来获得正确的DST调整.

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));
Run Code Online (Sandbox Code Playgroud)

版画

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
Run Code Online (Sandbox Code Playgroud)

因此,在阳光明媚的奥克兰,新西兰,我们在夏令时期为+12但是+13.

我的错.谢谢你的答案,让我看到了我的错误.

Jim*_*son 18

你看过DateTime构造函数了吗:

DateTime(DateTimeZone zone) 
Run Code Online (Sandbox Code Playgroud)

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

  • 我更喜欢`DateTime.now(DateTimeZone zone)`,因为我觉得它更明显. (6认同)

Mic*_*ker 14

怎么样:

DateTime utc = new DateTime(DateTimeZone.UTC);
DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles");
DateTime losAngelesDateTime = utc.toDateTime(tz);
Run Code Online (Sandbox Code Playgroud)


Jos*_*ter 10

最干净的方法

我发现以下是最干净的方法.

DateTime currentTime = DateTime.now( DateTimeZone.UTC );
Run Code Online (Sandbox Code Playgroud)

这将获得UTC的当前时间,但此值可以转换为另一个,DateTimeZone或者您可以DateTimeZone.UTC使用其他值替换DateTimeZone.

使用系统TimeZone

如果要将其设置为系统时区,可以使用以下命令:

DateTime currentTime = DateTime.now( DateTimeZone.getDefault() );
Run Code Online (Sandbox Code Playgroud)