ZetCode

Go datetime

last modified September 26, 2022

Go datetime tutorial shows how to work with datetime in Golang. The time package provides functionality for measuring and displaying time.

Definitions

A calendar time, also called an absolute time, is a point in the time continuum, for example July 29, 2021 at 13:02:5 CET. A time interval is a continuous part of the time continuum between two calendar times; for instance the hour between 15:00 and 19:00 on February 20, 2020. An elapsed time is the length of an interval, for example, 38 minutes.

An amount of time is a sum of elapsed times. The elapsed times do not need to be successive. When the work took us eleven hours, we might be working on different days. A period is the elapsed time of an interval between two events. CPU time is the amount of time for which a central processing unit (CPU) was used for processing instructions of a computer program or operating system. It is measured in clock ticks or seconds. An epoch is an instant in time chosen as the origin of a particular era. The Unix epoch is the time 00:00:00 UTC on 1 January 1970 (or 1970-01-01T00:00:00Z ISO 8601).

Wall time, also called real-world time or wall-clock time, refers to elapsed time as determined by a chronometer such as a wristwatch or wall clock. (The reference to a wall clock is how the term originally got its name.) Wall time differs from time as measured by counting microprocessor clock pulses or cycles.

$ go version
go version go1.18.1 linux/amd64

We use Go version 1.18.

Go current time example

The following example print the current date and time.

main.go
package main

import (
    "fmt"
    "time"
)

func main() {

    now := time.Now()
    fmt.Println("Current datetime:", now)
}

The example prints the current time with Now.

$ go run main.go
Current datetime: 2022-05-29 17:46:47.069217048 +0200 CEST m=+0.000013004

Go UTC time

Our planet is a sphere; it revolves round its axis. The Earth rotates towards the east, so the Sun rises at different times in different locations. The Earth rotates once in about 24 hours. Therefore, the world was divided into 24 time zones. In each time zone, there is a different local time. This local time is often further modified by daylight saving.

There is a pragmatic need for one global time. One global time helps to avoid confusion about time zones and daylight saving time. The UTC (Universal Coordinated time) was chosen to be the primary time standard. UTC is used in aviation, weather forecasts, flight plans, air traffic control clearances, and maps. Unlike local time, UTC does not change with a change of seasons.

$ timedatectl
               Local time: Ne 2022-05-29 17:48:07 CEST
           Universal time: Ne 2022-05-29 15:48:07 UTC
                 RTC time: Ne 2022-05-29 15:48:07
                Time zone: Europe/Bratislava (CEST, +0200)
System clock synchronized: yes
              NTP service: active
          RTC in local TZ: no

Our timezone is Central European Summer Time (CEST). The UTC offset, that is the difference between the local time and the UTC time, for our zone is 2 hours.

main.go
package main

import (
     "fmt"
     "time"
)

func main() {

     utc := time.Now().UTC()
     fmt.Println(utc)
}

The example prints the UTC time with the UTC function.

$ go run main.go
2022-05-29 15:50:07.413562417 +0000 UTC

Go datetime parts

In the following example, we print the parts of the current datetime.

main.go
package main

import (
    "fmt"
    "time"
)

func main() {

    now := time.Now()

    fmt.Println("Year:", now.Year())
    fmt.Println("Month:", now.Month())
    fmt.Println("Day:", now.Day())
    fmt.Println("Hour:", now.Hour())
    fmt.Println("Minute:", now.Minute())
    fmt.Println("Second:", now.Second())
    fmt.Println("Nanosecond:", now.Nanosecond())
}

We print the year, month, day, hour, minute, second, and nanosecond with the corresponding functions separately.

$ go run main.go
Year: 2022
Month: May
Day: 29
Hour: 17
Minute: 50
Second: 38
Nanosecond: 266573694

Go Date function

The time.Date function allows to create a datetime from the given moment int time.

main.go
package main

import (
     "fmt"
     "time"
)

func main() {
     t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
     fmt.Printf("Go launch date: %s\n", t.Local())
}

We pass the year, month, day, hour, minute, second, nanosecond, and location parameters to the time.Date function.

$ go run main.go
Go launch date: 2009-11-11 00:00:00 +0100 CET

Go format datetime

Go does not use the typical yyyy-mm-dd format specifier; it uses the following reference datetime format:

Mon Jan 2 15:04:05 -0700 MST 2006

We format the time how we structure this specific reference datetime.

main.go
package main

import (
    "fmt"
    "time"
)

func main() {

    now := time.Now()

    fmt.Println("Time: ", now.Format("15:04:05"))
    fmt.Println("Date:", now.Format("Jan 2, 2006"))
    fmt.Println("Timestamp:", now.Format(time.Stamp))
    fmt.Println("ANSIC:", now.Format(time.ANSIC))
    fmt.Println("UnixDate:", now.Format(time.UnixDate))
    fmt.Println("Kitchen:", now.Format(time.Kitchen))
}

The example displays the current time in custom and predefined formats.

fmt.Println("Date:", now.Format("Jan 2, 2006"))

This is an example of a custom datetime format.

fmt.Println("ANSIC:", now.Format(time.ANSIC))

This is an example of a predefined format.

$ go run main.go
Time:  17:51:45
Date: May 29, 2022
Timestamp: May 29 17:51:45
ANSIC: Sun May 29 17:51:45 2022
UnixDate: Sun May 29 17:51:45 CEST 2022
Kitchen: 5:51PM

Go parse datetime

The Parse function parses a formatted string and returns the time value it represents.

func Parse(layout, value string) (Time, error)

The layout defines the format by showing how the reference time. Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and convenient representations of the reference time.

main.go
package main

import (
     "fmt"
     "log"
     "time"
)

func main() {

     vals := []string{"2021-07-28", "2020-11-12", "2019-01-05"}

     for _, val := range vals {

          t, err := time.Parse("2006-01-02", val)

          if err != nil {

               log.Fatal(err)
          }

          fmt.Println(t)
     }
}

The example parses three date values.

$ go run main.go
2021-07-28 00:00:00 +0000 UTC
2020-11-12 00:00:00 +0000 UTC
2019-01-05 00:00:00 +0000 UTC

Go datetime arithmetic

To add or subtract datetimes we can use the Add and AddDate functions.

main.go
package main

import (
     "fmt"
     "time"
)

func main() {

     now := time.Now()

     t1 := now.Add(time.Hour * 27)
     fmt.Println(t1.Format(time.UnixDate))

     t2 := now.AddDate(2, 10, 11)
     fmt.Println(t2.Format(time.UnixDate))

     t3 := now.Add(-time.Hour * 6)
     fmt.Println(t3.Format(time.UnixDate))
}

In the code example, we perform three arithmetic operations.

t1 := now.Add(time.Hour * 27)

We add 27 hours.

t2 := now.AddDate(2, 10, 11)

We add 2 years, 10 months, and 11 days.

t3 := now.Add(-time.Hour * 6)

We subtract 6 hours.

$ go run main.go
Mon May 30 20:52:29 CEST 2022
Wed Apr  9 17:52:29 CEST 2025
Sun May 29 11:52:29 CEST 2022

Go datetime Duration

A duration is the time that has elapsed between two instants of time.

type Duration int64

A Duration type in Go represents the elapsed time between two instants as an int64 nanosecond count.

func (t Time) Sub(u Time) Duration

The Sub function returns the elapsed time between two time instants.

main.go
package main

import (
     "fmt"
     "time"
)

func main() {

     t1 := time.Date(2020, time.November, 10, 23, 0, 0, 0, time.UTC)
     t2 := time.Date(2021, time.July, 28, 16, 22, 0, 0, time.UTC)

     elapsed := t2.Sub(t1)

     fmt.Println(elapsed)
}

The example calculates the elapsed time between two time instants.

$ go run main.go
6233h22m0s
main.go
package main

import (
     "fmt"
     "time"
)

func main() {

     t2 := time.Now()

     year, _, _ := t2.Date()
     t1 := time.Date(year, 0, 0, 0, 0, 0, 0, time.Local)

     elapsed := time.Since(t1)

     fmt.Println(elapsed)
}

The Since function returns the time elapsed since the specified datetime. It is shorthand for time.Now().Sub(t).

$ go run main.go
4336h53m3.593593645s

Go datetime Location

A Location maps time instants to the zone in use at that time.

func (t Time) In(loc *Location) Time

The In function returns a time with a specific location.

main.go
package main

import (
     "fmt"
     "log"
     "time"
)

func main() {

     names := []string{
          "Local",
          "UTC",
          "Pacific/Galapagos",
          "Europe/Budapest",
          "Europe/Moscow",
          "Asia/Vladivostok",
          "Antarctica/Vostok",
          "America/New_York",
          "Africa/Tripoli",
     }

     now := time.Now()

     for _, name := range names {

          loc, err := time.LoadLocation(name)

          if err != nil {
               log.Fatal(err)
          }

          t := now.In(loc)

          fmt.Println(loc, ": ", t)
     }
}

The example gets the current local time and determines the corresponding time in different locations.

$ go run main.go
Local :  2022-05-29 17:53:24.652877602 +0200 CEST
UTC :  2022-05-29 15:53:24.652877602 +0000 UTC
Pacific/Galapagos :  2022-05-29 09:53:24.652877602 -0600 -06
Europe/Budapest :  2022-05-29 17:53:24.652877602 +0200 CEST
Europe/Moscow :  2022-05-29 18:53:24.652877602 +0300 MSK
Asia/Vladivostok :  2022-05-30 01:53:24.652877602 +1000 +10
Antarctica/Vostok :  2022-05-29 21:53:24.652877602 +0600 +06
America/New_York :  2022-05-29 11:53:24.652877602 -0400 EDT
Africa/Tripoli :  2022-05-29 17:53:24.652877602 +0200 EET

Go Unix time

The Unix time is the number of seconds since the Unix epoch. The Unix time is widely used in computing.

main.go
package main

import (
     "fmt"
     "time"
)

func main() {

     timestamp := time.Now().Unix()
     fmt.Printf("%d\n", timestamp)
}

We get the Unix time with Unix function.

$ go run main.go
1653839627

Go datetime comparison

To compare datetimes, we use the Equal, Before, and After functions.

main.go
package main

import (
     "fmt"
     "time"
)

func main() {

     var t1 = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
     var t2 = time.Date(2021, time.July, 28, 16, 22, 0, 0, time.UTC)
     var t3 = time.Date(2021, time.July, 28, 16, 22, 0, 0, time.UTC)

     if t1.Equal(t2) {

          fmt.Println("t1 and t2 are equal")
     } else {

          fmt.Println("t1 and t2 are not equal")
     }

     if t2.Equal(t3) {

          fmt.Println("t2 and t3 are equal")
     } else {

          fmt.Println("t2 and t3 are not equal")
     }

     if t1.Before(t2) {

          fmt.Println("t1 is before t2")
     }

     if t3.After(t1) {

          fmt.Println("t3 is after t1")
     }
}

In the code example, we compare three datetimes.

$ go run main.go
t1 and t2 are not equal
t2 and t3 are equal
t1 is before t2
t3 is after t1

In this tutorial, we have worked with date and time in Go.

List all Go tutorials.