在Go语言中使用字符串类型比较两个日期。

huangapple go评论85阅读模式
英文:

Comparing two dates in Go using string types

问题

最近,我一直在尝试找到一种方法来判断给定的日期是否大于或等于今天。GitHub Copilot建议我使用以下算法:

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

所以,我尝试了一些测试日期,结果总是正确的。然而,我想知道这是否是一种好的日期比较方法,或者它可能在任何时刻导致错误的响应?

提前谢谢你。

英文:

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 := &quot;2021-01-01&quot;
today := time.Now().Format(&quot;2006-01-02&quot;)
switch {
	case date == today:
		fmt.Println(&quot;Equal&quot;)

	case date &lt; today:
		fmt.Println(&quot;Less&quot;)

	case date &gt; today:
		fmt.Println(&quot;Greater&quot;)
}

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

答案1

得分: 3

我认为使用Unix格式的时间会得到更可预测的结果,但你现在的做法更快。

t, _ := time.Parse("2006-01-02", "2021-01-01")

date := t.Unix()
today := time.Now().Unix()

switch {
    case date == today:
        fmt.Println("相等")

    case date < today:
        fmt.Println("小于")

    case date > today:
        fmt.Println("大于")
}
英文:

I think you would get more predictable results working with time in unix format, but the way your doing it right now is faster.

t, _ := time.Parse(&quot;2006-01-02&quot;, &quot;2021-01-01&quot;)

date := t.Unix()
today := time.Now().Unix()

switch {
    case date == today:
        fmt.Println(&quot;Equal&quot;)

    case date &lt; today:
        fmt.Println(&quot;Less&quot;)

    case date &gt; today:
        fmt.Println(&quot;Greater&quot;)
}

答案2

得分: 1

如果你用相同位数表示两个日期(年、月、日的位数相同),并且字段的顺序是从高到低(年->月->日),那么这种比较总是正确的(字符串比较也是从左到右进行的)。

注意:当年份达到10000时,这种比较可能会给出错误的结果,因为第一个假设不成立(年份的位数不同)。如果你想处理超过9999年的年份,你需要用5位数字表示年份,所以2021必须写成02021

英文:

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.

huangapple
  • 本文由 发表于 2021年11月11日 02:44:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/69918631.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定