Working with Date and Time in Go

9 Oct 2020 ⏱️ 5 min
Working with Date and Time in Go

In this tutorial we will explore different ways to use time in Go. Golang provides us a package time that provides functionality for measuring and displaying time. This package will be all you need in most of the use cases.

A Time represents an instant in time with nanosecond precision.

Time in Go is based on location and can be used to display multiple formats (Days, hours, seconds). As per unix timestamp standard, even Go starts its time counter as zero on January 1st, 1970 at UTC. The current timestamp at the time of writing this tutorial is 1602249029

Ok, let’s get started with managing time in Go.


How to get current timestamp

The time.Time object helps us in getting the computation of time. You don’t want to write a function to compute seconds elapsed since 1st Jan, 1970 every time. This is where the time package comes to save you.

package main
import (
    "fmt"
    "time"
)

func main() {
    localTimeNow := time.Now()
    currentSeconds := localTimeNow.Unix()
    fmt.Println(“Time object:, localTimeNow)
    fmt.Println(“Time in seconds:, currentSeconds)
}

time.Now() returns the time.Time object. If you look at the output below, you’ll see that the time returned is the current local time. So, this might not be same if you are in different location across the globe.

currentSeconds represents the seconds passed since the Unix epoch (1 Jan, 1970 00:00:00).

Time object:  2020-10-09 18:52:19.229868 +0530 IST m=+0.000111168
Time in seconds:  1602249739
Time in nanoseconds:  205643000

Fetching Day, Month, Year

Time object provides a lot of other helper methods. You can use methods like Day(),Month() , Year(), Hour() and lot more as per need. Check all available methods here.

// Fetching current Day, Month and Year
time.Now().Day()
time.Now().Month()
time.Now().Year()

How to get time from timestamp

You might want to check date given a timestamp. Since, calculations in timestamp are easy to perform, people prefer converting to timestamp, performing operations and then converting it back to readable date format. We can use Unix() method to achieve this.

package main

import (
    "fmt"
    "time"
)

func main() {
    timestamp := int64(1602254086)
    date := time.Unix(timestamp, 0)
    fmt.Println(“Given timestamp to date :, date)
}

The above code results in date for given timestamp -

Given timestamp to date :  2020-10-09 20:04:46 +0530 IST

Time is standard formats

Time package provide number of formats in which time can be parsed. Let’s look at an example -

package main

import (
    "fmt"
    "time"
)

const (
    ISOformat    = "2006-01-02"
    USformat     = "January 2, 2006"
    RFC850format = "Monday, 02-Jan-06 15:04:05 UTC"
)

func main() {
    date :=2020-10-09"
    timeInISOformat, _ := time.Parse(ISOformat, date)
    fmt.Println(timeInISOformat)
    fmt.Println(timeInISOformat.Format(USformat))
    fmt.Println(timeInISOformat.Format(RFC850format))
}

The output for above code will be -

2020-10-09 00:00:00 +0000 UTC
October 9, 2020
Friday, 09-Oct-20 00:00:00 UTC

You can find other available formats here.


How to get time at certain location/timezones

The time.Time objects has a loc *Location attribute which helps us fetching time at certain timezones. Let’s see how to use this with an example. Note: The nil location means UTC.

package main

import (
    "fmt"
    "time"
)

const (
    timezoneJakarta = "Asia/Jakarta"
    timezoneAmerica = "America/New_York"
)

func main() {
    // Current local time (India for me)
    localTimeNow := time.Now()
    fmt.Println(“Local time in India is:, localTimeNow)

    jakartaLoc, err := time.LoadLocation(timezoneJakarta)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(“Local time in Jakarta is:, localTimeNow.In(jakartaLoc))

    americaLoc, err := time.LoadLocation(timezoneAmerica)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(“Local time in US is:, localTimeNow.In(americaLoc))
}

The above code will print current time in different timezones -

Local time in India is:  2020-10-09 19:31:51.771828 +0530 IST m=+0.000088151
Local time in Jakarta is:  2020-10-09 21:01:51.771828 +0700 WIB
Local time in US is:  2020-10-09 10:01:51.771828 -0400 EDT

Time in UTC, IST and other timezones

In place of specifying full timezone location we can also provide various time in short formats like UTC, IST, EST, MST etc. You can even fetch your current zone using Zone() method.

package main

import (
    "fmt"
    "time"
)

func main() {
    currentZone, offset := time.Now().Zone()
    fmt.Println(“Your Timezone :, currentZone)
    fmt.Println(“Offset in seconds from UTC:, offset)

    utcLoc, err := time.LoadLocation(“UTC”)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(“Local time UTC is:, time.Now().In(utcLoc))
}


How to modify date

There are multiple ways to achieve this. Two common one are -

  1. Converting to timestamp (seconds) and then easily modifying date by adding/subtracting seconds.
  2. Using AddDate() method from time package

Let’s see how it works -

package main

import (
    "fmt"
    "time"
)

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

    // Using AddDate() method
    tomorrow := t.AddDate(0, 0, 1)
    yesterday := t.AddDate(0, 0, -1)
    nextMonth := t.AddDate(0, 1, 0)
    nextYear := t.AddDate(1, 0, 0)

    fmt.Println(“Tomorrow using AddDate():, tomorrow)
    fmt.Println(“Yesterday:, yesterday)
    fmt.Println(“Next Month:, nextMonth)
    fmt.Println(“Next Year:, nextYear)

    // Using timestamp
    timestamp := t.Unix()
    timestampTomorrow := timestamp + 24*60*60
    tomorrow = time.Unix(timestampTomorrow, 0)

    fmt.Println(“Tomorrow using timestamp:, tomorrow)
}

The above code prints next day, month and year and explores both method to achieve this.

Tomorrow using AddDate():  2020-10-10 19:58:09.701298 +0530 IST
Yesterday:  2020-10-08 19:58:09.701298 +0530 IST
Next Month:  2020-11-09 19:58:09.701298 +0530 IST
Next Year:  2021-10-09 19:58:09.701298 +0530 IST
Tomorrow using timestamp:  2020-10-10 19:58:09 +0530 IST


Resources

There is a lot more to learn about Git which is out of scope for this basic articles. Here are some of the resources to learn.

Books to learn Golang


I hope you learned something new. Feel free to suggest improvements ✔️

I share regular updates and resources on Twitter. Let’s connect!

Keep exploring 🔎 Keep learning 🚀

Liked the content? Do support :)

Paypal - Mohit Khare
Buy me a coffee