golang can display date and time. In this article you will learn how to deal with date and time in golang.
Date is default, but time cannot go back earlier than 1970. Why? that’s when the logic was added to computers.
Date and time in golang
Example
The program below is an example of date and time in golang. The formatting is explicitly defined (%y for year, %m for month etc).
// Golang doesnt have strftime (%Y,%M,%d) etc.
// Instead use the time package.
package main
import (
"fmt"
"time"
)
func main() {
:= time.Now().UTC()
current .Println("Date: " + current.Format("2006 Jan 02"))
fmt.Println("Time: " + current.Format("03:04:05"))
fmt}
Strftime
But if you use the arrow library, you can use strftime style formatting. Install the package with:
go get github.com/bmuller/arrow/lib
Then run the code below:
package main
import (
"fmt"
"github.com/bmuller/arrow/lib"
)
func main() {
// formatting
.Println("Date: ", arrow.Now().CFormat("%Y-%m-%d"))
fmt.Println("Time: ", arrow.Now().CFormat("%H:%M:%S"))
fmt}
The code above displays the date and time. You can use an alternative formatting if you want.. The output will be similar to this:
Date : 2018-06-07
Time : 10:38:01
Exercises
- Display date in DD/MM/YYYY format