首页 > 文章列表 > golang 中的日期休息一个月

golang 中的日期休息一个月

279 2024-04-15
问题内容

我想在 golang 的约会中休息一个月,我有一个三月和二月的例子:

date := time.date(2023, time.march, 31, 0, 0, 0, 0, time.utc)

然后做这个:

period := date.adddate(0, -1, -0)

但是程序给了我:

original date: 2023-03-31 00:00:00 +0000 utc
date after rest: 2023-03-03 00:00:00 +0000 utc

我期望:

2023-02-28 00:00:00 +0000 UTC

同时,我希望每个月的休息都能动态进行。

谢谢。


正确答案


正如 go 自带的自动转换让你烦恼一样,你也可以利用它。

诀窍是如何获取上个月的天数。

// as there is no 0 day, it means the last day of the previous mouth
totday := time.date(y, m, 0, 0, 0, 0, 0, time.utc).day()

完整代码如下:

package main

import (
    "fmt"
    "time"
)

func previousMouth(t time.Time) time.Time {
    y, m, d := t.Date()

    curTotDay := time.Date(y, m+1, 0, 0, 0, 0, 0, time.UTC).Day()
    totDay := time.Date(y, m, 0, 0, 0, 0, 0, time.UTC).Day()
    if d == curTotDay {
        d = totDay
    }

    return time.Date(y, m-1, d, 0, 0, 0, 0, time.UTC)
}

func main() {
    date := time.Date(2023, time.March, 31, 0, 0, 0, 0, time.UTC)
    fmt.Println(previousMouth(date))
}

在线运行:goplayground