将给定区域的LocalTime转换为unix epoch秒而不使用java中的日期组件

时间:2017-09-26 15:41:10

标签: java unix-timestamp epoch java-time localdate

我们收到时间为小时= 11,分钟= 29,秒= 54,毫秒= 999以及时区信息。

如何将此时间转换为unix epoch毫秒而没有日期部分。 我试过这段代码:

    ZoneId zoneId = ZoneId.of("America/New_York");
    LocalDate now = LocalDate.now(zoneId);
    long epochMilli = ZonedDateTime.of(LocalDate.now(zoneId).atTime(11, 29, 20, 999 * 1000 * 1000), zoneId).toInstant().toEpochMilli();
    long unixEpocSeconds = epochMilli % (24 * 60 * 60 * 1000); //86400000

    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(zoneId));
    calendar.setTimeInMillis(unixEpocSeconds);
    System.out.println("( = " + (calendar.get(Calendar.HOUR)==11));
    System.out.println("( = " + (calendar.get(Calendar.MINUTE)==29));
    System.out.println("( = " + (calendar.get(Calendar.SECOND)==20));
    System.out.println("( = " + (calendar.get(Calendar.MILLISECOND)==999));

如何在没有日期组件的情况下获取unix纪元秒,即如何获得UTC区域中的毫秒数而不是给出zoneid。上面的代码运行找到zoneId = UTC

1 个答案:

答案 0 :(得分:2)

TL;博士

Duration.ofHours( 11L )
        .plusMinutes( 29L )
        .plusSeconds( 54L )
        .plusMillis( 999L ) 
        .toMillis()
  

41394999

时间跨度与时间

你的问题很困惑。 与UTC相比,没有日期的时间没有任何意义。自{1}}的Unix纪元参考日期以来的毫秒数用于跟踪日期和< / em>时间。

我怀疑你实际上是在处理一段时间,并且把它当作时间错误处理。一个是时间轴,另一个不是。

1970-01-01T00:00:00Z

与Java 8及更高版本捆绑在一起的java.time类包含Duration,用于处理未附加到时间轴的时间跨度。

这些方法采用Duration数据类型,因此尾随long

L

毫秒计数

你问了毫秒数,所以你走了。请注意数据丢失,因为Duration d = Duration.ofHours( 11L ).plusMinutes( 29L ).plusSeconds( 54L ).plusMillis( 999L ) ; 具有更精细的纳秒分辨率,因此在转换为毫秒时,您将丢掉任何更精细的一秒。

Duration
  

41394999

但我建议你使用毫秒计数代表时间轴上的时间跨度或时刻。更好地使用对象或标准化文本;请继续阅读。

ISO 8601

ISO 8601标准定义了用于将日期时间值表示为文本的实用明确格式。

这包括representation of durations。格式为long millis = d.toMillis() ; // Converts this duration to the total length in milliseconds. ,其中PnYnMnDTnHnMnS标记开头,而P将任意年 - 月 - 天的部分与任何小时 - 分钟 - 秒部分分开。

默认情况下,java.time类在Tparse方法中使用标准格式。

toString
  

PT11H29M54.999S

请参阅此code run live at IdeOne.com

您可以直接在java.time中解析这些字符串。

String output = d.toString() ;

我建议尽可能使用这种格式,当然在系统之间交换数据时。

在Java中工作时,传递Duration d = Duration.parse( "PT11H29M54.999S" ) ; 个对象而不仅仅是文本。

时间轴

您可以使用Duration对象执行日期时间数学运算。例如,在您的特定时区内获取当前时刻,并添加11个半小时。

Duration
  

now.toString():2017-09-27T07:23:31.651 + 13:00 [太平洋/奥克兰]

     

later.toString():2017-09-27T18:53:26.650 + 13:00 [太平洋/奥克兰]

对于UTC值,请致电ZoneId z = ZoneId.of( "Pacific/Auckland" ) ; ZonedDateTime now = ZonedDateTime.now( z ) ; ZonedDateTime later = now.plus( d ) ; toInstant类表示UTC时间轴上的一个时刻,分辨率为纳秒(小于毫秒)。

Instant