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

标签 go

我只想将日期值解析为 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/

相关文章:

html - 设置 gcloud appspot 域 - 找不到 URL 错误

go - 如何在 Golang 中转储结构的方法?

nginx - 无法使用 NginX/FastCGI 建立 Websocket 连接

testing - golang测试中的cpuprofile和memprofile

url - go URL 中的额外转义字符

go - 临时文件是暂时的吗?如果是这样多久?

go - 我可以创建共享测试实用程序吗?

go - 如何在golang中编写asm代码 "bsrl"

go - 如何让 Go 接受网络请求

arrays - Golang 通用 JSON 编码