如何计算UTC时间和当地时间之间的差异

时间:2017-01-11 16:22:18

标签: java date

我正在尝试从UTC时间戳获取本地时间并计算偏移量。 我的UTC时间= 1484063246 这是我的代码。

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       dateFormat.setTimeZone(TimeZone.getTimeZone("CET"));
       String formattedDate = dateFormat.format(new Date(1484063246L * 1000L)); 

formattedDate以日期格式返回。如何根据这些值计算UTC时间和本地时间之间的差异。如何根据服务器运行的位置设置TimeZone而不是硬编码“CET”。

3 个答案:

答案 0 :(得分:2)

如果我理解你的问题,你可以这样做(JSE> = 1.8):

.bit

import java.time.Instant; import java.time.ZoneId; Instant instant = Instant.ofEpochMilli(1484063246L * 1000L); // You can use this if you already have a Date object // Instant instant = dateInstance.toInstant(); // You can use this for current offset // Instant instant = Instant.now(); ZoneId.systemDefault().getRules().getOffset(instant); 返回系统默认(本地)ZoneId,systemDefault()返回指定时刻从该区域到UTC的偏移量。

e.g。

getOffset(instant)

+01:00 Europe/Berlin

-02:30

Canada/Newfoundland Z(关注任意数字转换!!)

详细了解official docs

编辑:删除了UTC类的使用,因为它可以避免导入(正如Basil Bourque的回答所暗示的那样)。顺便说一句Date类是旧的,但是一个非常简单且永不弃用的类。事实上,它是纯毫秒的轻量级抽象。

答案 1 :(得分:0)

以毫秒为单位获取当前时间戳,并从1484063246中减去。 从下面的示例开始。 您还需要检查偏移量是正还是负。

    long now = System.currentTimeMillis();
    long offset = now - 1484063246L * 1000;
    Date date = new Date(offset);
    DateFormat df = new SimpleDateFormat("HH:mm:ss");
    System.out.println(df.format(date));

答案 2 :(得分:0)

TL;博士

ZoneId.of( "Europe/Paris" )
      .getRules()
      .getOffset( 
          Instant.ofEpochMilli( 1_484_063_246L ) 
      ).getTotalSeconds()

小心'local'这个词

在Java日期时间类中,localLocalDateLocalDateTime中的单词LocalTime表示任何位置,否具体地点。这些类故意没有时区或偏移的概念。绝对在本课题的上下文中你想要什么。

避免遗留日期时间类

Answer by Linuslabo是正确的,并且使用java.time类朝着正确的方向前进,但不必要地涉及旧的遗留java.util.Date类。

避免旧的旧日期时间类(DateCalendarSimpleDateFormat等),因为它们已被证明是混乱,设计不佳和麻烦。现在取代java.time类。

使用java.time

Instant类代表UTC中时间轴上的一个时刻,分辨率为nanoseconds(小数部分最多九(9)位)。

milliseconds以来,您的输入似乎是epoch的计数。

请注意,Java允许数字文字中的下划线,以便人类更容易阅读。

Instant instant = Instant.ofEpochMilli( 1_484_063_246L );

您可以将其调整为时区,以查看某个地区的wall-clock time。以continent/region格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用诸如ESTCETIST之类的3-4字母缩写,因为它们不是真正的时区,不是标准化的,甚至不是唯一的( !)。

ZoneId zoneId = ZoneId.of( "Europe/Paris" );
ZonedDateTime zdt = instant.atZone( zoneId );

您可以通过ZoneId查询offset-from-UTC ZoneOffset ZoneRules Daylight Saving Time (DST),这似乎是您的问题的重点。由于as a total number of seconds等异常,偏移量会随时间变化。时区是过去,现在和将来的偏移的集合。因此,在向区域询问偏移时,您必须指定一个时刻。

ZoneOffset zoneOffset = zoneId.getRules().getOffset( instant );

如果需要,您可以获得抵消金额java.time

int offsetInSeconds = zoneOffset.getTotalSeconds() ;

关于java.time

legacy框架内置于Java 8及更高版本中。这些类取代了麻烦的旧java.util.Date日期时间类,例如CalendarSimpleDateFormat和& Joda-Time

现在位于maintenance modejava.time项目建议迁移到Oracle Tutorial类。

要了解详情,请参阅JSR 310。并搜索Stack Overflow以获取许多示例和解释。规范是Java SE 8

从哪里获取java.time类?

Interval项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如YearWeekYearQuartermore和{{3}}。

相关问题