format a date in to the format month day, year hour:minute:second.fff am/pm in go

In Go, you can format a date using the time package. Here's an example of how to format a date in the format "Month day, year hour:minute:second.fff am/pm":

main.go
package main

import (
	"fmt"
	"time"
)

func main() {
	t := time.Now()
	fmt.Println(t.Format("January 02, 2006 03:04:05.000 pm"))
}
133 chars
12 lines

In this example, we're using the Now() function of the time package to get the current time. We then call the Format() method on the time object and pass in a string that specifies the desired format.

The format string corresponds to different parts of the date, as follows:

  • January: The full name of the month (e.g. "January")
  • 02: The day of the month with leading zeroes (e.g. "01", "02", etc.)
  • 2006: The year (e.g. "2006")
  • 03: The hour (0-12) with leading zeroes (e.g. "01", "02", etc.)
  • 04: The minute with leading zeroes (e.g. "01", "02", etc.)
  • 05: The second with leading zeroes (e.g. "01", "02", etc.)
  • .000: The fractional second with milliseconds (e.g. "000", "123", etc.)
  • pm: The lower-case "am" or "pm" designator based on the time

Note that the format string is specific to the desired format, and the order and content of the different date components can be customized as necessary.

related categories

gistlibby LogSnag