How to convert a date time string to long (UNIX Epoch Time) in Java 8 (Scala)

落花浮王杯 提交于 2019-12-03 14:13:00
ETO

This one is more than two times shorter (only 3 method calls):

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

Btw, I would build the DateTimeFormatter outside of dateTimeStringToEpoch and pass it as a method parameter:

def dateTimeStringToEpoch(s: String, formatter: DateTimeFormatter): Long = 
     LocalDateTime.parse(s, formatter).toEpochSecond(ZoneOffset.UTC)

Having actually run a performance test, there is little difference in performance (barely a factor of 2) in initialising the DateTimeFormatter outside the method.

scala> val pattern = "yyyy/MM/dd HH:mm:ss"
pattern: String = yyyy/MM/dd HH:mm:ss

scala>   time(() => randomDates.map(dateTimeStringToEpoch(_, pattern)))
Took: 1216

scala>   time(() => randomDates.map(dateTimeStringToEpochFixed))
Took: 732

You may use the equivalent of the following Java code:

static long dateTimeStringToEpoch(String s, String pattern) {
    return DateTimeFormatter.ofPattern(pattern).withZone(ZoneOffset.UTC)
        .parse(s, p -> p.getLong(ChronoField.INSTANT_SECONDS));
}

Of course, processing DateTimeFormatter.ofPattern(pattern).withZone(ZoneOffset.UTC) implies work that could be avoided when encountering the same pattern string multiple times. Whether this amount of work is relevant for your application, depends on what is is doing beside this operation.

Can you try this one, based on what you have said, it is parsing UTC time, so I have this as a sample.

Instant.parse("2019-01-24T12:48:14.530Z").getEpochSecond

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!