Go: How to parse only date to 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 (

var dateToParse = "2016-03-31"

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

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

The output is this:

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.

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

Answered By – peterSO

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.