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.
1 2 3 4 5 6 7 8 9 | package 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“.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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")) } |
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
1 Comment
Awesome