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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Golang doesnt have strftime (%Y,%M,%d) etc.
// Instead use the time package.
package main

import (
"fmt"
"time"
)

func main() {
current := time.Now().UTC()
fmt.Println("Date: " + current.Format("2006 Jan 02"))
fmt.Println("Time: " + current.Format("03:04:05"))
}

Strftime

But if you use the arrow library, you can use strftime style formatting.
Install the package with:

1
go get github.com/bmuller/arrow/lib

Then run the code below:

1
2
3
4
5
6
7
8
9
10
11
12
package main

import (
"fmt"
"github.com/bmuller/arrow/lib"
)

func main() {
// formatting
fmt.Println("Date: ", arrow.Now().CFormat("%Y-%m-%d"))
fmt.Println("Time: ", arrow.Now().CFormat("%H:%M:%S"))
}

The code above displays the date and time. You can use an alternative formatting if you want..
The output will be similar to this:
1
2
Date : 2018-06-07
Time : 10:38:01

Exercises

  1. Display date in DD/MM/YYYY format