How to Get Current Date and Time in Golang

Channel: Linux
Abstract: 05 Mon")) //With weekday (Monday) fmt.Println(dt.Format("01-02-2006 1505 Mon")) //With weekday (Monday) fmt.Println(dt.Format("01-02-2006 15

This quick tutorial helps you to get current Date and Time in Go programming language. Let’s go through the tutorial to understand the uses of time package in your Go script.

Get Date and Time in Golang

You need to import the 「time」 package in your Go script to work with date and time. As an example use below script. I have also included fmt package to show formatted output on your screen.

package main import "fmt" import "time" func main() { dt := time.Now() fmt.Println("Current date and time is: ", dt.String()) }123456789package main import "fmt"import "time" func main() {    dt := time.Now()    fmt.Println("Current date and time is: ", dt.String())}

For testing copy above code in a go script and Run application on your system using Golang.

go run datetime.go

The result will be like below

Current date and time is:  2018-08-10 21:10:39.121597055 +0530 IST
Get Formatted Date and Time

It uses a predefined layout to format the date and time. The reference time used in the layouts is the specific time: 「Mon Jan 2 15:04:05 MST 2006「.

package main import "fmt" import "time" func main() { dt := time.Now() //Format MM-DD-YYYY fmt.Println(dt.Format("01-02-2006")) //Format MM-DD-YYYY hh:mm:ss fmt.Println(dt.Format("01-02-2006 15:04:05")) //With short weekday (Mon) fmt.Println(dt.Format("01-02-2006 15:04:05 Mon")) //With weekday (Monday) fmt.Println(dt.Format("01-02-2006 15:04:05 Monday")) //Include micro seconds fmt.Println(dt.Format("01-02-2006 15:04:05.000000")) //Include nano seconds fmt.Println(dt.Format("01-02-2006 15:04:05.000000000")) }12345678910111213141516171819202122232425package main import "fmt"import "time" func main() {    dt := time.Now()    //Format MM-DD-YYYY    fmt.Println(dt.Format("01-02-2006"))     //Format MM-DD-YYYY hh:mm:ss    fmt.Println(dt.Format("01-02-2006 15:04:05"))     //With short weekday (Mon)    fmt.Println(dt.Format("01-02-2006 15:04:05 Mon"))     //With weekday (Monday)    fmt.Println(dt.Format("01-02-2006 15:04:05 Monday"))     //Include micro seconds    fmt.Println(dt.Format("01-02-2006 15:04:05.000000"))     //Include nano seconds    fmt.Println(dt.Format("01-02-2006 15:04:05.000000000"))}

Execute above program using Golang and see output:

08-10-2018
08-10-2018 21:11:58
08-10-2018 21:11:58 Fri
08-10-2018 21:11:58 Friday
08-10-2018 21:11:58.880934
08-10-2018 21:11:58.880934320

Ref From: tecadmin

Related articles