Format time in Golang using time Package

The time package allows us to do time formatting in Go. This post aims to explore different formatting methods that can be applied for time formatting in Golang.

The required imports

For this, to work, we need the time package to be imported.

import "time"

Pattern-based formatting

Go supports pattern-based time formatting. A reference layout or pattern is set up and then used to create the formatted timestamp.

Go time package can also parse time, based on the string provided as a format which is a standard predefined layout. The standard layouts can be obtained from here.

Here are some examples of time formatting using layouts.

Examples

Here is some example of layout based formatted time.

package main

import (
	"fmt"
	"time"
)

func main() {
	t := time.Now()

	fmt.Println(t.Format("3:04PM")) // 8:54PM

	fmt.Println(t.Format("Jan-02-06")) // February 27, 2020

	fmt.Println(t.Format("Jan _2 15:04:05.000000")) // Feb 27 21:07:10.714500

	fmt.Println(t.Format("3:04:05 PM")) // 9:07:10 PM

	fmt.Println(t.Format("Mon, 02 Jan 2006 15:04:05 MST")) // Thu, 27 Feb 2020 21:07:10 IST
}

The predefined layouts are created by a committee and it can only be used for a layout. A custom user-defined layout will return a wrongly formatted time.

Parse time

Parse can help determine wrongly formatted input and return errors upon receiving the wrong input. Here is the parse function in action.

_, e := time.Parse("3:04PM", "12:04AM")
if e != nil {                           // error checking
	fmt.Println(e)
}

This function is helpful when checking whether formatting is done correctly or not.

Uses of time formatting

Time formatting helps to show what is needed to be shown. Without time formatting precise log generation is a bit problematic as we may not need all the information and more information can only be confusing.