dategocomparisondate-comparison

Comparing two dates in Go using string types


Recently, I've had been trying to find a way to know if a given date is greater or equal than today. The GitHub Copilot has suggested I should use the following algorithm:

date := "2021-01-01"
today := time.Now().Format("2006-01-02")
switch {
    case date == today:
        fmt.Println("Equal")

    case date < today:
        fmt.Println("Less")

    case date > today:
        fmt.Println("Greater")
}

// Less

So, I've tried with some testing dates and, the result is always correct. However, I'd like to know whether if this is a good way to make date comparisons or it may lead to a wrong response at any moment?

Thank you in advance.


Solution

  • If you represent both dates with equal number of digits (same width for all year, month and date values), and since the order of fields are from higher priority to lower (year -> month -> day), this will always be correct (string comparison also proceeds from left-to-right).

    Note: When the year reaches 10000, this comparison may give wrong results, because the first assumption will not be true (same width for all year values). If you want to handle years beyond 9999, you'll have to represent years with 5 digits, so 2021 must be written as 02021.