Search code examples
javadateinstantdatetimeformatter

How to convert a TemporalAccessor a milliseconds timestamp (using Instant)


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).


Solution

  • 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);