ZetCode

Go datetime

last modified July 28, 2021

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 current time example

The following example print the current date and time.

current_time.go
package main

import (
    "fmt"
    "time"
)

func main() {

    now := time.Now()

    fmt.Println("The current datetime is:", now)
}

The example prints the current time with Now.

$ go run current_time.go 
The current datetime is: 2021-07-28 13:56:36.752128647 +0200 CEST m=+0.000101652

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: Wed 2021-07-28 14:16:27 CEST
 Universal time: Wed 2021-07-28 12:16:27 UTC
       RTC time: Wed 2021-07-28 12:16:27
      Time zone: Europe/Bratislava (CEST, +0200)
System clock synchronized: no
    NTP service: n/a
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.

utc_time.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 utc_time.go 
2021-07-28 12:20:32.680513857 +0000 UTC

Go datetime parts

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

current_time_parts.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 datetime_parts.go 
Year: 2021
Month: July
Day: 28
Hour: 13
Minute: 59
Second: 1
Nanosecond: 125562318

Go Date function

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

date_fun.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 date_fun.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.

format_time.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 format_time.go 
Time:  14:33:40
Date: Jul 28, 2021
Timestamp: Jul 28 14:33:40
ANSIC: Wed Jul 28 14:33:40 2021
UnixDate: Wed Jul 28 14:33:40 CEST 2021
Kitchen: 2:33PM

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.

parse_time.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 parse_time.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.

add_sub.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 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 add_sub.go 
Thu Jul 29 19:31:39 CEST 2021
Sat Jun  8 16:31:39 CEST 2024
Wed Jul 28 10:31:39 CEST 2021

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.

sub_fun.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 subfun.go 
6233h22m0s
since_fun.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 since_fun.go 
5775h48m13.805216342s

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.

locations.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 locations.go 
Local :  2021-07-28 15:59:37.702026813 +0200 CEST
UTC :  2021-07-28 13:59:37.702026813 +0000 UTC
Pacific/Galapagos :  2021-07-28 07:59:37.702026813 -0600 -06
Europe/Budapest :  2021-07-28 15:59:37.702026813 +0200 CEST
Europe/Moscow :  2021-07-28 16:59:37.702026813 +0300 MSK
Asia/Vladivostok :  2021-07-28 23:59:37.702026813 +1000 +10
Antarctica/Vostok :  2021-07-28 19:59:37.702026813 +0600 +06
America/New_York :  2021-07-28 09:59:37.702026813 -0400 EDT
Africa/Tripoli :  2021-07-28 15:59:37.702026813 +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.

unix_time.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 unix_time.go 
1627476026

Go datetime comparison

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

comparing.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 example, we compare three datetimes.

$ go run comparing.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.