Home »
Golang »
Golang Programs
Golang program to get current date and time
Here, we are going to learn how to get current date and time in Golang (Go Language)?
Submitted by Nidhi, on March 21, 2021 [Last updated : March 04, 2023]
How to get current date and time in Golang?
Problem Solution:
In this program, we will create a string and get the current date and time using time.Now() function. After that, we will print the result on the console screen.
Program/Source Code:
The source code to get the current date and time is given below. The given program is compiled and executed successfully.
Golang code to get current date and time
// Golang program to get the current date and time
package main
import "fmt"
import "time"
func main() {
var currentDateAndTime string
currentDateAndTime = time.Now().String()
fmt.Println("Current date and time\n", currentDateAndTime)
}
Output:
Current date and time
2021-03-21 05:50:43.783414013 +0000 UTC m=+0.000076722
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 created a string currentDateTime. Then we called the time.Now() function to get the current date and time. The time.Now() function return the object of the time type, here we used String() function to convert the time into the string. After that, we printed the result on the console screen.
Get Formatted Date and Time
package main
import "fmt"
import "time"
func main() {
dtobj := time.Now()
// MM-DD-YYYY format
fmt.Println(dtobj.Format("01-02-2006"))
// MM-DD-YYYY HH:MM:SS format
fmt.Println(dtobj.Format("01-02-2006 15:04:05"))
// MM-DD-YYYY HH:MM:SS DAY format
fmt.Println(dtobj.Format("01-02-2006 15:04:05 Mon"))
// MM-DD-YYYY HH:MM:SS DAY (full) format
fmt.Println(dtobj.Format("01-02-2006 15:04:05 Monday"))
// MM-DD-YYYY HH:MM:SS Micro Seconds format
fmt.Println(dtobj.Format("01-02-2006 15:04:05.000000"))
// MM-DD-YYYY HH:MM:SS Nano Seconds format
fmt.Println(dtobj.Format("01-02-2006 15:04:05.000000000"))
}
Output:
03-21-2021
03-21-2021 05:57:59
03-21-2021 05:57:59 Sun
03-21-2021 05:57:59 Sunday
03-21-2021 05:57:59.116203
03-21-2021 05:57:59.116203254
Golang Date & Time Programs »