gpt4 book ai didi

Go:如何只解析日期到时间。时间?

转载 作者:IT王子 更新时间:2023-10-29 02:02:56 25 4
gpt4 key购买 nike

我只想将日期值解析为 time.Time。例如我有这种格式的日期:2016-03-31,我想解析它,比如:time.Parse(FORMAT, "2016-03-31").

但总是失败。

仅使用此格式解析日期的正确格式字符串是什么?

我有下面的代码作为示例,它也在 Playground 上:https://play.golang.org/p/0MNLr9emZd

package main

import (
"fmt"
"time"
)

var dateToParse = "2016-03-31"

func main() {
format := "2006-12-01"
parseDate(format)
}

func parseDate(format string) {
t, err := time.Parse(format, dateToParse)
if err != nil {
fmt.Println("Format:", format)
fmt.Println(err)
fmt.Println("")
return
}
fmt.Println("Works Format:", format)
fmt.Println(t)
fmt.Println("")
}

输出是这样的:

Format: 2006-12-01
parsing time "2016-03-31" as "2006-12-01": cannot parse "-31" as "2"

最佳答案

Package time

These are predefined layouts for use in Time.Format and Time.Parse. The reference time used in the layouts is the specific time:

Mon Jan 2 15:04:05 MST 2006

which is Unix time 1136239445. Since MST is GMT-0700, the reference time can be thought of as

01/02 03:04:05PM '06 -0700

To define your own format, write down what the reference time would look like formatted your way; see the values of constants like ANSIC, StampMicro or Kitchen for examples.

对 yyyy-mm-dd 使用 format := "2006-01-02"

关于Go:如何只解析日期到时间。时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45372490/

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