Home > Back-end >  Java analog of time.Parse from GoLang
Java analog of time.Parse from GoLang

Time:01-31

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

CodePudding user response:

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.ofPattern("uuuuMMdd"));
var instant = date.atStartOfDay(ZoneOffset.UTC).toInstant();

CodePudding user response:

Since the result of the line of Go you provided includes an offset, a zone and the time of day, you will have to explicitly attach those and use a specific formatter in Java:

public static void main(String[] args) {
    // example input
    String date = "20060102";
    // pattern needed for parsing
    String pattern = "uuuuMMdd";
    // the parser
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
    // parse the date first
    LocalDate localDate = LocalDate.parse(date, dtf);
    // then add the minimum time of day and the desired zone id
    ZonedDateTime zdt = ZonedDateTime.of(localDate, LocalTime.MIN, ZoneId.of("UTC"));
    // the formatter
    DateTimeFormatter dtfOut = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss Z VV", Locale.ENGLISH);
    // the result of the Go statement
    String expected = "2006-01-02 00:00:00  0000 UTC";
    // print the result
    System.out.println("Expected: "   expected);
    System.out.println("Actual:   "   zdt.format(dtfOut));
}

Output:

Expected: 2006-01-02 00:00:00  0000 UTC
Actual:   2006-01-02 00:00:00  0000 UTC

Posts about y and u (actually accepted answers to the questions)

  • Related