gpt4 book ai didi

time - 获取 time.Time 月份的最后一天

转载 作者:IT王子 更新时间:2023-10-29 01:24:35 28 4
gpt4 key购买 nike

当我有一个time.Time时:

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

如何获得代表 1 月 31 日的 time.Time?这个例子很简单,但是当日期在二月时,最后一天可能是 28 日或 29 日。

最佳答案

Package time

func Date

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

Date returns the Time corresponding to

yyyy-mm-dd hh:mm:ss + nsec nanoseconds

in the appropriate zone for that time in the given location.

The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 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())
}

输出:

2016 January 29
2016 January 31

关于time - 获取 time.Time 月份的最后一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35182556/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com