如何在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不存在

是否不能使用 ZoneOffset#UTC ?

LocalDateTime.parse(s, dateTimeFormatter).atOffset(ZoneOffset.UTC).toInstant().toEpochMilli()

@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()