如何使用golang获取当月的开始日期和结束日期?

时间:2018-10-31 04:26:14

标签: go time

我想编写一个简单的golang程序,只告诉我当前月份的开始日期和月份的结束日期。还有一个条件是,如果用户将输入月份和年份,那么它将给我该年份和月份的开始日期和结束日期。为此,我尝试了以下程序,但不会给我正确的结果:

package main

import (
  "fmt"
  "time"
)

func main() {
  var year int
  var month int
  year = 2018
  month = 1
  if year != 0 && month != 0 {
     t2 := time.Now().AddDate(year, month, 0)
    fmt.Println(t2)
  } else {
    t2 := time.Now().AddDate(0, 0, 0)
    fmt.Println(t2)
 }
}

go playground link

任何人都可以告诉我如何纠正该程序。

谢谢。

3 个答案:

答案 0 :(得分:1)

例如,

package main

import (
    "fmt"
    "time"
)

func monthInterval(y int, m time.Month) (firstDay, lastDay time.Time) {
    firstDay = time.Date(y, m, 1, 0, 0, 0, 0, time.UTC)
    lastDay = time.Date(y, m+1, 1, 0, 0, 0, -1, time.UTC)
    return firstDay, lastDay
}

func main() {
    var (
        y int
        m time.Month
    )

    y, m, _ = time.Now().Date()
    first, last := monthInterval(y, m)
    fmt.Println(first.Format("2006-01-02"))
    fmt.Println(last.Format("2006-01-02"))

    y, m = 2018, time.Month(2)
    first, last = monthInterval(y, m)
    fmt.Println(first.Format("2006-01-02"))
    fmt.Println(last.Format("2006-01-02"))
}

输出:

2018-10-01
2018-10-31
2018-02-01
2018-02-28

游乐场:https://play.golang.org/p/TkzCo9jLpZR

答案 1 :(得分:1)

您可以自己处理time package in golang

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    fmt.Println(BeginningOfMonth(t))
    fmt.Println(EndOfMonth(t))

    // If you need only date use Format(). But remember Format() will return as a string
    dateFormat := "2006-01-02"
    fmt.Println(BeginningOfMonth(t).Format(dateFormat))
    fmt.Println(EndOfMonth(t).Format(dateFormat))
}

func BeginningOfMonth(t time.Time) time.Time {
    return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
}

func EndOfMonth(t time.Time) time.Time {
    return BeginningOfMonth(t).AddDate(0, 1, 0).Add(-time.Second)
}

输出:

  

2018-10-01 00:00:00 +0530 IST

     

2018-10-31 23:59:59 +0530 IST

     

2018-10-01

     

2018-10-31

答案 2 :(得分:0)

嗯,您只需要看下面我为您编写的代码,然后阅读注释并学习即可。通过引用thisthis time package in golang

package main

import (
 "fmt"
 "strings"
 "time"
)

func main() {
 var year int
 year = 2019
 currentLocation := time.Now().Location() // got current location
 if year != 0 {
    firstOfMonth := time.Date(year, time.February, 1, 0, 0, 0, 0, currentLocation) // first date of the month
    fmt.Println(firstOfMonth)
    lastOfMonth := firstOfMonth.AddDate(0, 1, -1).Format("2006-01-02 00:00:00 -0000") // last date of the month 
    fmt.Println(lastOfMonth)
    onlyDate := strings.Split(lastOfMonth, " ")
    fmt.Println(onlyDate[0])
 } 
}

go playground link

已编辑

package main

import (
 "fmt"
 "time"
)

func main() {
 month := 1
 fmt.Println(time.Month(month))
}

converting int month into time link playground

希望它会对您有所帮助:)。