Time Formatting in Golang
Last Updated :
17 May, 2020
Golang supports time formatting and parsing via pattern-based layouts. To format time, we use the Format() method which formats a time.Time object.
Syntax:
func (t Time) Format(layout string) string
We can either provide custom format or predefined date and timestamp format constants are also available which are shown as follows.
Layouts must use the reference time Mon Jan 2 15:04:05 MST 2006 to show the pattern with which to format/parse a given time/string.
Example 1:
package main
import (
"fmt"
"time"
)
func main() {
current_time := time .Now()
fmt.Printf( "%d-%02d-%02dT%02d:%02d:%02d-00:00\n" ,
current_time.Year(), current_time.Month(), current_time.Day(),
current_time.Hour(), current_time.Minute(), current_time.Second())
fmt.Println(current_time.Format( "2006-01-02 15:04:05" ))
fmt.Println(current_time.Format( "2006-January-02" ))
fmt.Println(current_time.Format( "2006-01-02 3:4:5 pm" ))
}
|
Output:
2009-11-10T23:00:00-00:00
2009-11-10 23:00:00
2009-November-10
2009-11-10 11:0:0 pm
Example 2:
package main
import (
"fmt"
"time"
)
func main() {
current_time := time .Now()
fmt.Println( "ANSIC: " , current_time.Format( time .ANSIC))
fmt.Println( "UnixDate: " , current_time.Format( time .UnixDate))
fmt.Println( "RFC1123: " , current_time.Format( time .RFC1123))
fmt.Println( "RFC3339Nano: " , current_time.Format( time .RFC3339Nano))
fmt.Println( "RubyDate: " , current_time.Format( time .RubyDate))
}
|
Output:
ANSIC: Tue Nov 10 23:00:00 2009
UnixDate: Tue Nov 10 23:00:00 UTC 2009
RFC1123: Tue, 10 Nov 2009 23:00:00 UTC
RFC3339Nano: 2009-11-10T23:00:00Z
RubyDate: Tue Nov 10 23:00:00 +0000 2009