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:
- 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
Also, bonus question, is it efficient? Is there any overhead to creating the DateTimeFormatter
via DateTimeFormatter.ofPattern(pattern)
? If so why?