1

Example input string: Mon Feb 07 07:47:04 UTC 2022

I have tried various different patterns, and none work, mostly I get the error:

java.time.format.DateTimeParseException: Text 'Mon Feb 07 07:47:04 UTC 2022' could not be parsed at index 4

This is my code (it's spark/scala but using Java libraries as is allowed). I need to convert strings of the form above, into a numeric value in seconds since the Unix epoch. I don't have control over the input format (it's from an external API) - I could use string manipulation on it if I really had to, but ideally just need to find a pattern that the formatter accepts.

import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
import java.time.ZoneOffset;
import java.time.LocalDateTime;

def df = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("EEE LLL d H:m:s 'UTC' uuuu").toFormatter(Locale.ENGLISH);

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

println(dateTimeStringToEpoch("Mon Feb 07 07:47:04 UTC 2022"));

Thanks

Alex Kerr
  • 956
  • 15
  • 44
  • 1
    Tested in "pure" Java and it works. The value is: 1644220024. This is probably a problem in the library version. – pringi Feb 10 '22 at 12:43
  • In java you can try this code: new SimpleDateFormat("EEE MMM dd HH:mm:ss 'UTC' yyyy").parse("Mon Feb 07 07:47:04 UTC 2022").getTime(); – user3458271 Feb 10 '22 at 13:26
  • The `uuuu` in your pattern makes no sense. As per https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html this denotes a day of the week where as you supply a year in your examples. Replace it with `YYYY` instead. – Alex Feb 10 '22 at 13:49
  • You probably need `MMM` instead of `LLL` in your format pattern string. While `LLL` may work on some Java versions, it is not strictly correct when the string includes a day of month. – Ole V.V. Feb 10 '22 at 13:53
  • 1
    @Alex The `uuuu` is correct. You are referring to the wrong documentation. – Ole V.V. Feb 10 '22 at 13:57
  • @user3458271 Please don’t suggest the long outdated and notoriously troublesome `SimpleDateFormat` class. the OP is already wisely using [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Feb 10 '22 at 13:58
  • I believe that the question in your title [is answered by Arvind Kumar Avinash here](https://stackoverflow.com/a/67323750/5772882). – Ole V.V. Feb 10 '22 at 14:00
  • 1
    A simple way: set `df` to `DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT)` and then have your method return `ZonedDateTime.parse(s, df).toEpochSecond()`. It will give inaccurate results for years before the Julian/Gregorian crossover in 1583, though. – Ole V.V. Feb 10 '22 at 14:10

0 Answers0