Home »
Golang »
Golang Programs
Golang program to print date and time in different formats using format constants
Here, we are going to learn how to print date and time in different formats using format constants in Golang (Go Language)?
Submitted by Nidhi, on March 21, 2021 [Last updated : March 04, 2023]
How to print date and time in different formats in Golang?
Problem Solution:
In this program, we will get the current date and time. Then we print date and time in different formats using format() constants.
Program/Source Code:
The source code to print date and time in different formats using format constants is given below. The given program is compiled and executed successfully.
Golang code to print date and time in different formats using format constants
// Golang program to print date and time in
// different formats using format constant
package main
import "fmt"
import "time"
func main() {
//Get the current date and time.
currentDateTime := time.Now()
ANSIC_FORMAT := currentDateTime.Format(time.ANSIC)
UnixDate_FORMAT := currentDateTime.Format(time.UnixDate)
RFC1123_FORMAT := currentDateTime.Format(time.RFC1123)
RFC3339Nano_FORMAT := currentDateTime.Format(time.RFC3339Nano)
RubyDate_FORMAT := currentDateTime.Format(time.RubyDate)
//print different date and time formats
fmt.Println("Date time formats")
fmt.Println("ANSIC : ", ANSIC_FORMAT)
fmt.Println("UnixDate : ", UnixDate_FORMAT)
fmt.Println("RFC1123 : ", RFC1123_FORMAT)
fmt.Println("RFC3339Nano : ", RFC3339Nano_FORMAT)
fmt.Println("RubyDate : ", RubyDate_FORMAT)
}
Output:
Date time formats
ANSIC : Sun Mar 21 06:18:50 2021
UnixDate : Sun Mar 21 06:18:50 UTC 2021
RFC1123 : Sun, 21 Mar 2021 06:18:50 UTC
RFC3339Nano : 2021-03-21T06:18:50.512415661Z
RubyDate : Sun Mar 21 06:18:50 +0000 2021
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.
In the main() function, we called time.Now() to get the current date and time. After that, we convert to date and time into different formats and print the result on the console screen.
Golang Date & Time Programs »