Golang : time.Time.Format() function example

package time

Golang : time.Time.Format() function usage example. Useful in changing the time layout/format from one type to another type.

See reference section below for more formats accessible by time.[format name]. For example : time.ANSIC or time.RubyDate

 package main

 import (
 "fmt"
 "time"
 )

 func main() {

 layOut := "Jan 2, 2006 at 3:04pm (MST)"

 timePresent := time.Now()

 fmt.Println("Original : ", timePresent)

 timeLayOut := timePresent.Format(layOut)

 fmt.Println("After format : ", timeLayOut)

 timeANSIC := timePresent.Format(time.ANSIC)

 fmt.Println("After ANSIC : ", timeANSIC)

 timeUnixDate := timePresent.Format(time.UnixDate)

 fmt.Println("After UnixDate : ", timeUnixDate)

 timeRubyDate := timePresent.Format(time.RubyDate)

 fmt.Println("After RubyDate : ", timeRubyDate)

 timeRFC850 := timePresent.Format(time.RFC850)

 fmt.Println("After RFC850 : ", timeRFC850)
 }

Sample output :

Original : 2015-08-06 11:36:36.504592541 +0800 MYT

After format : Aug 6, 2015 at 11:36am (MYT)

After ANSIC : Thu Aug 6 11:36:36 2015

After UnixDate : Thu Aug 6 11:36:36 MYT 2015

After RubyDate : Thu Aug 06 11:36:36 +0800 2015

After RFC850 : Thursday, 06-Aug-15 11:36:36 MYT

References :

 ANSIC = "Mon Jan _2 15:04:05 2006"
 UnixDate = "Mon Jan _2 15:04:05 MST 2006"
 RubyDate = "Mon Jan 02 15:04:05 -0700 2006"
 RFC822 = "02 Jan 06 15:04 MST"
 RFC822Z = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
 RFC850 = "Monday, 02-Jan-06 15:04:05 MST"
 RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST"
 RFC1123Z = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
 RFC3339 = "2006-01-02T15:04:05Z07:00"
 RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
 Kitchen = "3:04PM"
 // Handy time stamps.
 Stamp = "Jan _2 15:04:05"
 StampMilli = "Jan _2 15:04:05.000"
 StampMicro = "Jan _2 15:04:05.000000"
 StampNano  = "Jan _2 15:04:05.000000000"

http://golang.org/pkg/time/#Time.Format

Advertisement