format a date in to the format october 13, 2014 in go

main.go
package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Date(2014, time.October, 13, 0, 0, 0, 0, time.UTC)
    formattedDate := t.Format("January 2, 2006")
    fmt.Println(formattedDate)
}
208 chars
13 lines

In the code above, we create a time.Time object representing the date October 13, 2014. We then use the Format() method to format the date according to the string "January 2, 2006", which produces the desired result of "October 13, 2014".

The string "January 2, 2006" may seem arbitrary, but it is a special reference date used in go's time package formatting. Each of the components of the string corresponds to a different part of the date:

  • January represents the full name of the month
  • 2 represents the day of the month, formatted with a leading zero if necessary
  • 2006 represents the year, formatted with all four digits

By using this specific string as a reference, we can format dates in a wide variety of styles.

related categories

gistlibby LogSnag