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

To format a date into the "yyyy-mm-dd hh:mm:ss" format in Go, you can use the time package to parse a date string and then format it using a layout string.

Here's an example:

main.go
package main

import (
    "fmt"
    "time"
)

func main() {
    // create a date
    date := time.Date(2021, time.August, 26, 15, 30, 0, 0, time.UTC)

    // format the date
    layout := "2006-01-02 15:04:05"
    formattedDate := date.Format(layout)

    fmt.Println(formattedDate) // output: 2021-08-26 15:30:00
}
317 chars
18 lines

In this example, we created a time.Time object with the year 2021, the month August, the day 26th, and the time 15:30:00. We then used the Format() method to format the date using the layout string "2006-01-02 15:04:05", which represents the year, month, day, hour, minute, and second in the format we want. The result is "2021-08-26 15:30:00".

related categories

gistlibby LogSnag