dsds661730652211 2017-07-28 11:35
浏览 27
已采纳

如何只解析date.time?Time?

I want to parse only date value to time.Time. For example I have date in this format: 2016-03-31, and I want to parse it, like: time.Parse(FORMAT, "2016-03-31").

But it always fail.

What is the correct format string to use to parse only date with this format?

I have the code below as example, it is on playground also: 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("")
}

The output is this:

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

1条回答 默认 最新

  • dongweng6241 2017-07-28 12:00
    关注

    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.

    Use format := "2006-01-02" for yyyy-mm-dd.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟