Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: How to parse only date to time.Time?

Tags:

go

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"
like image 454
Azize Avatar asked Jul 28 '17 11:07

Azize


1 Answers

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.

like image 158
peterSO Avatar answered Oct 05 '22 23:10

peterSO