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() {
  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:


go get github.com/bmuller/arrow/lib

Then run the code below:


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:


Date : 2018-06-07
Time : 10:38:01

Exercises

  1. Display date in DD/MM/YYYY format