【问题标题】:get the first and last dates of the previous 3 months in Go在 Go 中获取前 3 个月的第一个和最后一个日期
【发布时间】:2020-08-18 08:27:00
【问题描述】:

如何在 Go 中获取最近 3 个月的第一个和最后一个日期? 示例:

{"start": "2020-05-01", "end": "2020-07-31"}

【问题讨论】:

  • 你试过什么? Go 有一个带有许多实用程序的 time 包。

标签: go time


【解决方案1】:

你可以使用 golang time 包。

currentTime := time.Now()

last3Month := currentTime.AddDate(0,-3,0)

goneDaysOfMonth := last3Month.Day()

firstDay := last3Month.AddDate(0,0,-goneDaysOfMonth+1)
lastDay  := last3Month.AddDate(0,3,-goneDaysOfMonth)

timeLayout := "2006-01-02"

fmt.Println(firstDay.Format(timeLayout))
fmt.Println(lastDay.Format(timeLayout))

Go Playground

【讨论】:

    【解决方案2】:

    @ttrasn 的答案很好用(你绝对应该使用 time 包!)但是我觉得值得发布一种替代方法 (playground):

    year, month, _ := currentTime.Date()
    startTime := time.Date(year, month-3, 1, 0, 0, 0, 0, currentTime.Location())
    endTime := startTime.AddDate(0, 3, 0).Add(-time.Nanosecond)
    
    const layout = "2006-01-02"
    fmt.Println(startTime.Format(layout), endTime.Format(layout))
    

    使用Time.Date 可以轻松地将startTime 设置为所需月份的开始(时间组件设置为午夜)。请注意,time.Date 将正确处理负月份。

    要计算出结束时间,我们先加上三个月,然后减去一纳秒(将时间拉回到上个月的月底)。

    今天运行(以 UTC 为单位)计算的完整值是:

    startTime: 2020-05-01 00:00:00 +0000 UTC
    endTime:   2020-07-31 23:59:59.999999999 +0000 UTC
    

    使用@ttrasn 的解决方案将是:

    firstDay: 2020-05-01 08:56:46.000001 +0000 UTC
    lastDay:  2020-07-31 08:56:46.000001 +0000 UTC
    

    (时间部分取决于currentTime 的时间部分)。

    所以我的解决方案的好处是计算的时间范围涵盖了整个月。这与您的要求没有直接关系(因为未使用时间组件),但可能很重要(例如在进行数据库查询时)。

    【讨论】:

      猜你喜欢
      • 2021-03-22
      • 2012-05-29
      • 2013-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      相关资源
      最近更新 更多