format a date in to the format 'yyyy-mm-dd' in go

To format a date in Go, we can use the time.Format() method to format it into a particular string layout. Here's an example of how to format a date to the yyyy-mm-dd format in Go:

main.go
package main

import (
    "fmt"
    "time"
)

func main() {
    inputDate := "2021-08-12"
    t, err := time.Parse("2006-01-02", inputDate)
    if err != nil {
        fmt.Println(err)
    }
    
    formattedDate := t.Format("2006-01-02")
    fmt.Println(formattedDate)
}
274 chars
18 lines

In this example, we first parse the input date string using the time.Parse() method and specify its format layout as 2006-01-02, which represents the year, month, and day values in the input date string. The time.Parse() method returns a time.Time value, which we can then format into our desired string layout using the time.Format() method with the yyyy-mm-dd format layout of 2006-01-02.

Executing this program will output 2021-08-12, which is the formatted date string with the yyyy-mm-dd format layout.

related categories

gistlibby LogSnag