dongqie5529 2018-10-31 04:26
浏览 621

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

I want to make a simple program of golang which only tell me the current month start date and and month's end date. There is also a condition in this is that if the user will entered the month and year then it will give me the start date and end date of that year and month. For this I have tried the below program but it will not giving me the right results:

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

Can any body tell me how I will correct the program.

Thanks in advance.

  • 写回答

3条回答 默认 最新

  • duanrang2627 2018-10-31 05:03
    关注

    Umm You have to just see the below code I have written for you and just read the comments and learn it. By taking the reference of this and this 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

    Edited

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

    converting int month into time link playground

    Hope it will help you:).

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起