如何在Java 8(Scala)中将日期时间字符串转换为长(UNIX纪元时间)毫秒 [英] How to convert a date time string to long (UNIX Epoch Time) Milliseconds in Java 8 (Scala)

查看:201
本文介绍了如何在Java 8(Scala)中将日期时间字符串转换为长(UNIX纪元时间)毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题解决了几秒钟的情况:

This question solves the case for seconds: How to convert a date time string to long (UNIX Epoch Time) in Java 8 (Scala)

但是,如果我想要毫秒,似乎必须使用

But if I want milliseconds it seems I have to use

def dateTimeStringToEpoch(s: String, pattern: String): Long = 
    LocalDateTime.parse(s, DateTimeFormatter.ofPattern(pattern))
      .atZone(ZoneId.ofOffset("UTC", ZoneOffset.ofHours(0)))
      .toInstant().toEpochMilli

对于我在另一个问题中详述的4个问题(我不喜欢的主要内容是魔术文字"UTC"和魔术数字0),这很难看.

which is ugly for the 4 issues I detail in the other question (main things I don't like is the magic literal "UTC" and the magic number 0).

不幸的是,以下内容无法编译

Unfortunately the following does not compile

def dateTimeStringToEpoch(s: String, pattern: String): Long = 
     LocalDateTime.parse(s, DateTimeFormatter.ofPattern(pattern))
                  .toEpochMilliSecond(ZoneOffset.UTC)

因为toEpochMilliSecond不存在

推荐答案

是否不能使用 @Andreas在评论中指出,ZoneOffset是-a ZoneId,因此您可以使用

As @Andreas points out in the comments, ZoneOffset is-a ZoneId, so you could use

def dateTimeStringToEpoch(s: String, pattern: String): Long = 
    LocalDateTime.parse(s, DateTimeFormatter.ofPattern(pattern))
      .atZone(ZoneOffset.UTC)
      .toInstant()
      .toEpochMilli()

这篇关于如何在Java 8(Scala)中将日期时间字符串转换为长(UNIX纪元时间)毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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