获得一个月的最后一天.时间

Kir*_*ril 5 time go

当我有一个time.Time:

// January, 29th
t, _ := time.Parse("2006-01-02", "2016-01-29")
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到time.Time代表1月31日的?这个例子很简单,但是当二月有一个日期时,最后一天可能是28日或29日.

pet*_*rSO 6

包装时间

功能日期

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
Run Code Online (Sandbox Code Playgroud)

Date返回对应的Time

yyyy-mm-dd hh:mm:ss + nsec纳秒

在给定位置的那个时间的适当区域.

月,日,小时,分钟,秒和nsec值可能超出其通常范围,并将在转换期间进行标准化.例如,10月32日转换为11月1日.

例如,规范化日期,

package main

import (
    "fmt"
    "time"
)

func main() {
    // January, 29th
    t, _ := time.Parse("2006-01-02", "2016-01-29")
    fmt.Println(t.Date())
    // January, 31st
    y,m,_ := t.Date()
    lastday:= time.Date(y,m+1,0,0,0,0,0,time.UTC)
    fmt.Println(lastday.Date())
}
Run Code Online (Sandbox Code Playgroud)

输出:

2016 January 29
2016 January 31
Run Code Online (Sandbox Code Playgroud)