Time in go: unix, readable date and back

Let's see how to handle time and date in Go. Go has a build in function for managing time. You will see how to get the current unix time, how to force to 0 the seconds, how to parse the go time object to a readable date with year, month, day, minute, seconds. Finally you will learn how to go back to unix using the readable date.

Code to get the current unix timestamp in go

Here is the basic code to get the current time.

nowTime := time.Now()

Example

In this little example you will see how to get the current time in go and print it as the current unix timestamp.

You will then see how to round the time and set the seconds to zero.

The time is then printend in a readable format.

And finally, given the readable format, the string is converted back to a time golang object.

You will then see how to add hours or days to a go time object.

time.go
package main

import (
	"fmt"
	"time"
)

func main() {
	//get current unix timestamp
	nowTime := time.Now()
	fmt.Println(nowTime.Unix())

	//round the time and set the seconds to zero
	roundedTime := time.Date(nowTime.Year(), nowTime.Month(), nowTime.Day(), nowTime.Hour(), nowTime.Minute(), 0, 0, nowTime.Location())
	fmt.Println(roundedTime.Unix())

	//format the time to YYYY-MM-DD hh:mm
	readable := roundedTime.Format("2006-01-02 15:04")
	fmt.Println(readable)

	//let's convert back to unix
	if backToUnix, err := time.ParseInLocation("2006-01-02 15:04", readable, nowTime.Location()); err==nil{
		fmt.Println(backToUnix.Unix())
	}

    //add one day and format
    fmt.Println(roundedTime.Add(24*time.Hour).Format("2006-01-02 15:04"))

}

Format to a readable date, the codes

Here are the golang strings to format a date in a readable way.

  • Long month: January
  • Short month: Jan
  • Numer of the month: 1
  • Numer of the month with zero: 01
  • Long week day: Monday
  • Week day: Mon
  • Day: 2
  • Day with zero: 02
  • Hour: 15
  • Hour 12: 3
  • Hour 12 with zero: 03
  • Minute: 4
  • Minute with zero: 04
  • Seconds: 5
  • Seconds with zero: 05
  • Year: 2006
  • Short year: 06
  • pm/am: PM or pm

Other articles