Go Date and Time Formatting

 
 

Golang Date and Time formatting can be achieved quite easy and can be very handy when for example we need to name a database, database table, table field or maybe even a file. It really doesn’t matter what you need it for but in this particular short tutorial we will explain how to format date and time using Golang, in the end you may combine these as you want in order to achieve the right format for your project. The code used in this tutorial has been tested with Go 1.12.2 but it should work just fine with any other Go versions.

Code

Let’s now create a new main.go file and use the code below:


package main

import (
	"fmt"
	"time"
)

func main() {

	GetDateTime := time.Now()

	fmt.Println("Month and year:", GetDateTime.Format("012006"))
	fmt.Println("Just the day:", GetDateTime.Format("02"))
	fmt.Println("Current time:", GetDateTime.Format("150405"))

}

Run the code

Save the main.go file and let’s run it:


$ go run main.go

Output

The console output should look similar to this one listed below where we can notice that Date and Time were formatted as expected:


Month and year: 042019
Just the day: 07
Current time: 211951

Video

No video posted for this page.

Screenshots

No screenshots posted for this page.

Source code

No code posted for this page.

About this page

Article
Go Date and Time Formatting
Author
Category
Published
07/04/2019
Updated
23/04/2019
Tags

Share this page

If you found this page useful please share it with your friends or colleagues.