3

I am trying to convert a TemporalAccessor to milliseconds unix timestamp but I am getting an error in some cases.

Here is a code sample to reproduce the problem :

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendPattern("yyyy-MM-dd HH:mm:ss")
        .appendFraction(ChronoField.MICRO_OF_SECOND, 0, 6, true)
        .toFormatter();
    TemporalAccessor accessor = formatter.parse("1970-01-01 00:01:00.00");
    Instant instant = Instant.from(accessor);
    Instant.EPOCH.until(instant, ChronoUnit.MILLIS);

Here is the error I am getting :

Exception in thread "main" java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: {},ISO resolved to 1970-01-01T00:01 of type java.time.format.Parsed

I am getting this error only with this date format so the problem may come from my DateTimeFormatter (originally i was using an other one way more generic and I am only getting the error for this format).

  • As an aside instead of `Instant.EPOCH.until(instant, ChronoUnit.MILLIS);` just use `instant.toEpochMilli()`. – Ole V.V. Sep 30 '21 at 10:03
  • The string "1970-01-01 00:01:00.00" does not represent an instant. You still need a timezone/offset for that to be resolved to an instant. – Sweeper Sep 30 '21 at 10:11

1 Answers1

2

You need to specify the timezone in your DateTimeFormatter as follows:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendPattern("yyyy-MM-dd HH:mm:ss")
        .appendFraction(ChronoField.MICRO_OF_SECOND, 0, 6, true)
        .toFormatter()
        .withZone(ZoneId.systemDefault());
TemporalAccessor accessor = formatter.parse("1970-01-01 00:01:00.00");
Instant instant = Instant.from(accessor);
Instant.EPOCH.until(instant, ChronoUnit.MILLIS);
João Dias
  • 16,277
  • 6
  • 33
  • 45
  • The problem is that it seems that the method withZone overide eventual zoneId parsed with the formatter (at least in Java 8, in Java 11 it seems to keep the zoneId parsed idependently of the use of withZone() ) –  Oct 06 '21 at 10:39
  • But your pattern has no Zone data, nor the String you are trying to parse. – João Dias Oct 06 '21 at 10:41
  • it's true sorry. I tried to produce minimalist code to reproduce the problem. I open a new issue here with the new problem : https://stackoverflow.com/questions/69464683/why-date-parsing-using-datetimeformatter-gives-different-result-depending-on-jav?noredirect=1#comment122779893_69464683 –  Oct 06 '21 at 11:47