如何在Java 8(Scala)中将日期时间字符串转换为long(UNIX Epoch Time) [英] How to convert a date time string to long (UNIX Epoch Time) in Java 8 (Scala)
问题描述
我想要一些pattern
中的字符串的UNIX纪元时间(Posix Time,Unix Time),该字符串采用常规格式(即UTC).请使用Java 8,而不是Joda或旧Java.
I want the UNIX Epoch Time (Posix Time, Unix Time) of a string in some pattern
, the string is in normal format (so UTC). Please using Java 8, not Joda or old Java.
(For milliseconds please see How to convert a date time string to long (UNIX Epoch Time) Milliseconds in Java 8 (Scala))
到目前为止,我有以下内容,但出于多种原因,我对此很讨厌:
So far I have the below, but I hate this for a number of reasons:
- 对于日期最常见的事情(转换为UNIX Epoch Time),它太冗长了. 7种方法要求应为1.
- 它必须指定UTC,但可以肯定的是,UTC只是一个默认值,为什么我必须在此处明确说明?
- 它具有字符串文字
"UTC"
- 它有一个魔术数字
ZoneOffset.ofHours(0)
- It's way too verbose for what is the most common thing to do with dates (convert to UNIX Epoch Time). 7 method calls for what should be 1.
- It has to specify UTC, but surely UTC is just a default, why do I have to be explicit here?
- It has a string literal
"UTC"
- It has a magic number
ZoneOffset.ofHours(0)
到目前为止,我最好的:
My best so far:
def dateTimeStringToEpoch(s: String, pattern: String): Long =
LocalDateTime.parse(s, DateTimeFormatter.ofPattern(pattern))
.atZone(ZoneId.ofOffset("UTC", ZoneOffset.ofHours(0)))
.toInstant().getEpochSeconds
还有,奖金问题,效率高吗?通过DateTimeFormatter.ofPattern(pattern)
创建DateTimeFormatter
是否有任何开销?如果可以,为什么?
Also, bonus question, is it efficient? Is there any overhead to creating the DateTimeFormatter
via DateTimeFormatter.ofPattern(pattern)
? If so why?
推荐答案
此解决方案要短两倍以上(仅3个方法调用):
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)
顺便说一句,我将在dateTimeStringToEpoch
之外构建DateTimeFormatter
并将其作为方法参数传递:
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)
实际上已经进行了性能测试,所以在方法之外初始化DateTimeFormatter
的性能几乎没有差异(几乎是2倍).
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
这篇关于如何在Java 8(Scala)中将日期时间字符串转换为long(UNIX Epoch Time)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!