Search code examples
javadatedatetimeparsingdatetime-format

Java analog of time.Parse from GoLang


I am rewriting piece of GO code to java and I have doubths about the following snippet.

Go code:

time.Parse("20060102", someString);

Is it analog of ?

ZonedDateTime zdt = ZonedDateTime.parse(credElements[0], DateTimeFormatter.ofPattern("yyyyMMdd")

Solution

  • A quick look at the Go documentation reveals that:

    A Time represents an instant in time with nanosecond precision.

    Which is similar to Java's Instant type.

    Also, from the docs of Parse,

    Elements omitted from the layout are assumed to be zero or, when zero is impossible, one, so parsing "3:04pm" returns the time corresponding to Jan 1, year 0, 15:04:00 UTC (note that because the year is 0, this time is before the zero Time).

    [...]

    In the absence of a time zone indicator, Parse returns a time in UTC.

    Knowing this, we can first create a LocalDate from your string that does not contain any zone or time information, then "assume" (as the Go documentation calls it) that it is at the start of day, and at the UTC zone, in order to convert it to an Instant:

    var date = LocalDate.parse(someString, DateTimeFormatter.BASIC_ISO_DATE);
    var instant = date.atStartOfDay(ZoneOffset.UTC).toInstant();