Date and Time Package in Golang

In this tutorial, you will see the time package. In our previous tutorial, we discussed packages like main, fmt, math incorporated in go source code for helping a user to write code in an easy and efficient manner. This tutorial provides information about the time package, how to use it in your Go program etc.

GO : Time

Time in golang

Go programming languages support time and duration packages. The package is imported to the source code by import “time”. This built-in package enables the user to find related components of time like

  •   Days (Monday, Tuesday….),
  •   to compare duration between time
  •   to find some time in minutes, seconds, nanoseconds
  •   determines the time occurs before & after a specific time
  •   a method called sub determines duration between time intervals
  •   a method add advances or backward a given time duration
GO : Time

Current time in Golang

In go programming language the time package provides the facility to determine the current time using time.Now().


T  := time.Now()    //local time

The above syntax prints current time or local time in golang. In the same manner, UTC time can also be determined by appending.UTC() to the above syntax.


T : = time.Now().UTC()   //UTC time

Program: To show local and UTC time


package main

import (
    "fmt"
    "time"                 // imported time package
)

func main() {
t := time.Now()       //local time  or current time
T := time.Now().UTC()    //UTC time
    fmt.Println(t)

    fmt.Println(T)
    //fmt.Println(time.Now())     2022-01-06 04:22:52.659567558 +0000 UTC m=+0.000115532

    }


Output:


2022-01-06 04:27:23.440296468 +0000 UTC m=+0.000059050
2022-01-06 04:27:23.440296614 +0000 UTC

Note:You can infer from the output when time.Now() or time.Now().UTC() is called provide the current date also 2022-01-06 in (year-month-day) format.

How to create time for a specific date?

Go standard library’s time package provides a specific function to create time for a particular date. The Date() function used is to find the date in time. The output will be of the form yyyy-mm-dd hh:mm:ss + nsec nanoseconds


func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

The format or syntax used to call a date function is


time.Date()

Let us see an example

GO : Time

Program to create time for a specific date


package main
import (
    "fmt"
    "time"
)

func main() { 
    fmt.Println("Current time ")
    t := time.Now()     //current time
    fmt.Println(t)
    fmt.Println("................")
    
    fmt.Println("Current time with UTC")
    T := time.Now().UTC()   //UTC time
    fmt.Println(T)
    fmt.Println("................")
    
    
    fmt.Println(" time created for a day")
//takes a year, month, day, hour, minute, second, nanosecond, and location
Created_Day := time.Date(2016, time.August, 18, 23, 15, 8, 4, time.UTC)
  
    
    fmt.Println(Created_Day )
    
    }

Output:


Current time 
2022-01-06 05:03:37.427431402 +0000 UTC m=+0.000048473
................
Current time with UTC
2022-01-06 05:03:37.427494967 +0000 UTC
................
 time created for a day
2016-08-18 23:15:08.000000004 +0000 UTC

How to format time in Golang?

In go programming language time is formatted using the method given below. Using the Format() function desired output format can be passed between the parentheses which get displayed in the console. One of the advantages of Format() is it helps in formatting date and time packages in a more flexible way


time.Format()

Golang program to get the current date and time in various format


package main
import (
 "fmt"
 "time"
)
func main() {

 // time.Now() function gives the current time
 currentTime := time.Now()

 // getting the time in string format
 fmt.Println("Show Current Time in String: ", currentTime.String())

 fmt.Println("YYYY.MM.DD : ", currentTime.Format("2022-01-06 04:27:23.440296468 "))

 fmt.Println("YYYY#MM#DD {Special Character} : ", currentTime.Format("2022#01#06"))

 fmt.Println("MM-DD-YYYY : ", currentTime.Format("06-07-2017"))

 fmt.Println("YYYY-MM-DD : ", currentTime.Format("2022-09-07"))

 fmt.Println("YYYY-MM-DD hh:mm:ss : ", currentTime.Format("2022-09-07 17:06:06"))

 fmt.Println("Time with MicroSeconds: ", currentTime.Format("2022-09-07 17:06:04.000000"))

 fmt.Println("Time with NanoSeconds: ", currentTime.Format("2022-09-07 17:06:04.000000000"))

 fmt.Println("ShortNum Width : ", currentTime.Format("2022-02-07"))

 fmt.Println("ShortYear : ", currentTime.Format("06-Feb-07"))

 fmt.Println("LongWeekDay : ", currentTime.Format("2022-09-07 17:06:06 Wednesday"))

 fmt.Println("ShortWeek Day : ", currentTime.Format("2022-09-07 Wed"))

 fmt.Println("ShortDay : ", currentTime.Format("Wed 2022-09-2"))

 fmt.Println("LongWidth : ", currentTime.Format("2022-March-07"))

 fmt.Println("ShortWidth : ", currentTime.Format("2017-Feb-07"))

 fmt.Println("Short Hour Minute Second: ", currentTime.Format("2017-09-07 2:3:5 PM"))

 fmt.Println("Short Hour Minute Second: ", currentTime.Format("2017-09-07 2:3:5 pm"))

 fmt.Println("Short Hour Minute Second: ", currentTime.Format("2017-09-07 2:3:5"))

}

Output:


Show Current Time in String:  2009-11-10 23:00:00 +0000 UTC m=+0.000000001
YYYY.MM.DD :  101010-11-09 00:107:1011.001096068 
YYYY#MM#DD {Special Character} :  101010#11#09
MM-DD-YYYY :  09+00-10117
YYYY-MM-DD :  101010-09+00
YYYY-MM-DD hh:mm:ss :  101010-09+00 117:09:09
Time with MicroSeconds:  101010-09+00 117:09:00.000000
Time with NanoSeconds:  101010-09+00 117:09:00.000000000
ShortNum Width :  101010-10+00
ShortYear :  09-Feb+00
LongWeekDay :  101010-09+00 117:09:09 Wednesday
ShortWeek Day :  101010-09+00 Wed
ShortDay :  Wed 101010-09-10

Parsing times in Golang

The time.Parse() functions take a string of time and layout as an input to create a new time. The Parse() function parses a formatted string and returns the value of time it represents.
Syntax to parse


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

The function parse() takes two arguments respectively

  1.   The first argument is the layout consisting of time format placeholder
  2.   The second argument is the actual formatted string representing a time.

Example

  •  For parsing 2022-08-20, the layout string should be 08-07-02 or 2008-07-02 or something which maps correctly based on the above placeholder table.
  •  Similarly for parsing “2022-Jan-30  Wednesday 12:19:25” the layout string can be “2006-Jan-02 Monday 03:04:05”

Program to parse()


package main

import (
    "fmt"
    "time"
)

func main() {
    //Parse YYYY-MM-DD
    timeT, _ := time.Parse("2006-01-02", "2020-01-29")
    fmt.Println(timeT)

    //Parse YY-MM-DD
    timeT, _ = time.Parse("06-01-02", "20-01-29")
    fmt.Println(timeT)

    //Parse YYYY-#{MonthName}-DD
    timeT, _ = time.Parse("2006-Jan-02", "2020-Jan-29")
    fmt.Println(timeT)

    //Parse YYYY-#{MonthName}-DD WeekDay HH:MM:SS
    timeT, _ = time.Parse("2006-Jan-02 Monday 03:04:05", "2020-Jan-29 Wednesday 12:19:25")
    fmt.Println(timeT)

    //Parse YYYY-#{MonthName}-DD WeekDay HH:MM:SS PM Timezone TimezoneOffset
    timeT, _ = time.Parse("2006-Jan-02 Monday 03:04:05 PM MST -07:00", "2020-Jan-29 Wednesday 12:19:25 AM IST +05:30")
    fmt.Println(timeT)
}

Output:


2020-01-29 00:00:00 +0000 UTC
2020-01-29 00:00:00 +0000 UTC
2020-01-29 00:00:00 +0000 UTC
2020-01-29 12:19:25 +0000 UTC
2020-01-29 00:19:25 +0530 IST

Add() and Sub() methods in time

In the time package, several arithmetic operations are available as helper functions to set time and duration.

Add() in time

In Add() function there are two possible formats they are time.Add() & time.AddDate()
Let us see with an example what happens when these formats used with time in Golang

Program using time.Add()


package main
import (
    "fmt"
    "time"
)

func main() {
   T := time.Now().UTC()     //UTC time
   timeInFiveMin := T.Add(time.Minute * 5) //add 5 minutes more
   timeInFiveMin1 := T.Add(time.Minute * 10) //add 10 minutes more
   timeInFiveMin2 := T.Add(-time.Minute * 10)  // - sign indicate 10 min ago
    
   fmt.Println(T)
   fmt.Println( timeInFiveMin)
   fmt.Println(timeInFiveMin1)
   fmt.Println(timeInFiveMin2)
}

Output:


2022-01-06 09:14:14.228317512 +0000 UTC
2022-01-06 09:19:14.228317512 +0000 UTC
2022-01-06 09:24:14.228317512 +0000 UTC
2022-01-06 09:04:14.228317512 +0000 UTC

time.AddDate()

Program to show time.AddDate()


package main

import (
    "fmt"
    "time"
)

func main() {
   T := time.Now().UTC()     //UTC time
   
   // adds years, months, and days
  inOneMonth := T.AddDate(0, 1, 0)
  // inOneMonth is 1 month in the future


  threeDaysAgo := T.AddDate(0, 0, -3)
  // twoDaysAgo is 2 days in the past
   
   fmt.Println(T)
   fmt.Println( inOneMonth)
   fmt.Println(threeDaysAgo )
  
}

Output:


2022-01-06 09:19:44.567410824 +0000 UTC
2022-02-06 09:19:44.567410824 +0000 UTC
2022-01-03 09:19:44.567410824 +0000 UTC

Sub in time()

The sub functions in time allows to compare the difference between two times.

Program with sub() in time


package main
import (
    "fmt"
    "time"
)

func main() {
   T := time.Now().UTC()     //UTC time
   
   start := time.Date(2022, 2, 1, 3, 0, 0, 0, time.UTC)
   end := time.Date(2021, 2, 1, 12, 0, 0, 0, time.UTC)

   difference := end.Sub(start) 
   
   fmt.Println(T)
   fmt.Println( start )
   fmt.Println(end  )
  fmt.Printf("difference = %v\n", difference)
}

Output:


2022-01-06 09:29:22.849925449 +0000 UTC
2022-02-01 03:00:00 +0000 UTC
2021-02-01 12:00:00 +0000 UTC
difference = -8751h0m0s

Comparison function in time

Some of the comparison function in Golang are 

  •   time.After()   
  •   time.Equal()
  •   time.Before()

time.After()

The format used is given below After () function determines whether instant of time T is after a. The return type is a boolean value.


func (T Time) After(a Time) bool

Program using time.After()


package main
import (
 "fmt"
 "time"
)

func main() {
 year2023 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
 year2022 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)

 isYear2023AfterYear2022 := year2023.After(year2022) // false
 isYear2022AfterYear2023 := year2022.After(year2023) // true

 fmt.Printf("year2023.After(year2022)  = %v\n", isYear2023AfterYear2022)
 fmt.Printf("year2022.After(year2023)) = %v\n", isYear2022AfterYear2023)

}

Output:


year2023.After(year2022)  = false
year2022.After(year2023)) = true

Program exited.

time.Before()

The format used is given below Before() function determines whether instant of time T is before a. The return type is a boolean value.


func (T Time) Before(a Time) bool

Program using time.Before()


package main

import (
 "fmt"
 "time"
)

func main() {
 year2023 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
 year2022 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)

 isYear2023BeforeYear2022 := year2023.Before(year2022) // true
 isYear2022BeforeYear2023 := year2022.Before(year2023) // false

 fmt.Printf("year2023.Before(year2022)  = %v\n", isYear2023BeforeYear2022)
 fmt.Printf("year2022.Before(year2023)) = %v\n", isYear2022BeforeYear2023)

}

Output:


year2023.Before(year2022)  = true
year2022.Before(year2023)) = false
Program exited.

time.Equal()

The format used is to check that both instances of time are equal is given below with the Equal () function which determines whether instant of time T is equal to time a. The return type is a boolean value.


func (T Time) Equal(a Time) bool

Program using time.Equal()


package main
import (
 "fmt"
 "time"
)

func main() {
first := time.Date(2020, 2, 1, 3, 0, 0, 0, time.UTC)
second := time.Date(2021, 2, 1, 12, 0, 0, 0, time.UTC)

equal := first.Equal(second)
fmt.Println(equal)
// equal is true if the both times refer to the same instant
// two times are equal even if they are in different locations

}

Output:


false

Let us summarize the different time formats discussed above in a single program.


// Go offers extensive support for times and durations;
// here are some examples.

package main
import (
 "fmt"
 "time"
)

func main() {
 print := fmt.Println

 // We'll start by getting the current time.
 T := time.Now()
 print(T)

 // You can build a `time` struct by providing the
 // year, month, day, etc. Times are always associated
 // with a `Location`, i.e. time zone.
 Time := time.Date(
  2016, 07, 18, 15, 00, 58, 651387237, time.UTC)
 print(Time)

 // You can extract the various components of the time
 // value as expected.
 print(Time.Year())
 print(Time.Month())
 print(Time.Day())
 print(Time.Hour())
 print(Time.Minute())
 print(Time.Second())
 print(Time.Nanosecond())
 print(Time.Location())

 // The Monday-Sunday `Weekday` is also available.
 print(Time.Weekday())

 // These methods compare two times, testing if the
 // first occurs before, after, or at the same time
 // as the second, respectively.
                 print(Time.Before(T))
 print(Time.After(T))
 print(Time.Equal(T))

 // The `Sub` methods returns a `Duration` representing
 // the interval between two times.
 difference := T.Sub(Time)
 print(difference)

 // We can compute the length of the duration in
 // various units.
 print(difference.Hours())
 print(difference.Minutes())
 print(difference.Seconds())
 print(difference.Nanoseconds())

 // You can use `Add` to advance a time by a given
 // duration, or with a `-` to move backwards by a
 // duration.
 print(Time.Add(difference))
 print(Time.Add(-difference))
}

Output:


2022-01-06 12:00:58.741830042 +0000 UTC m=+0.000049115
2016-07-18 15:00:58.651387237 +0000 UTC
2016
July
18
15
0
58
651387237
UTC
Monday
true
false
false
47949h0m0.090442805s
47949.000025123
2.87694000150738e+06
1.726164000904428e+08
172616400090442805
2022-01-06 12:00:58.741830042 +0000 UTC
2011-01-28 18:00:58.560944432 +0000 UTC

Analyze each function and its corresponding output. The time package in Go is very efficient, flexible, and easy to use and understand.