Nikhil Joshi
Nikhil Joshi

Reputation: 817

Convert date from DD-MON-YY to YYYYMMDD

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.

Upvotes: 1

Views: 3243

Answers (2)

Sarath Sadasivan Pillai
Sarath Sadasivan Pillai

Reputation: 7091

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

Upvotes: 5

Dharma Saputra
Dharma Saputra

Reputation: 1674

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")

Upvotes: 2

Related Questions