1

In GoLang, how should I convert date from DD-MON-YY to YYYYMMDD format?

My input is: 9-Nov-17
Expected output is: 20171109

But when I do below:

t, err := time.Parse("20060102", "9-Nov-17")

Golang returns error:

Error: parsing time "9-Nov-17" as "20060102": cannot parse "v-17" as "2006"

Please help.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Nikhil Joshi
  • 817
  • 2
  • 12
  • 34
  • 2
    Possible duplicate of [Parsing date string in golang](https://stackoverflow.com/questions/25845172/parsing-date-string-in-golang) – tgogos Nov 23 '17 at 09:51
  • 1
    "9-Nov-17" is not a date in the format of "20060102" so of course you get an error. – Jonathan Hall Nov 23 '17 at 10:59

2 Answers2

5

You have to parse the time in the current format and then format it into the expected format using Format function

Check the answer below

package main

import (
    "fmt"
    "time"
)

func main() {
    // Parse a time value from a string in dd-Mon-yy format.
    t, _ := time.Parse("2-Jan-06", "9-Nov-17")
    //Format and print time in yyyymmdd format
    fmt.Println(t.Format("20060102"))
}

play link here : goplayground

2

There something called layout while parsing and formatting time in go. This layout will always formatted based on Mon Jan 2 15:04:05 -0700 MST 2006 time value. As example if you have input 2017 November 22, then the layout should be2006 January 02:

// example 1          -- layout ---      --- input -----
t, err := time.Parse("2006 January 02", "2017 November 22")
// example 2
t, err := time.Parse("02-01-2006", "22-11-2017")
Dharma Saputra
  • 1,524
  • 12
  • 17
  • The [reference time](https://golang.org/pkg/time/#pkg-constants) can also be thought of `01/02 03:04:05PM '06 -0700`, which is easy to remember (like counting from 1 to 7) – tgogos Nov 23 '17 at 09:46
  • @tgogos: And `01/02 15:04:05PM '06 -0700` for 24-hour clocks (15 = 12 + 03). – peterSO Nov 23 '17 at 15:18