Time and date are crucial components of a lot of software, from time management utilities to web applications. As a programmer, you need to know how to manipulate time and date in whichever language you use.

In Go, the time package bundles the functions for time and date manipulation. You can access these functions in any source file by importing that package.

So, what does it mean to manipulate time and date, and how can you manipulate time and date in Go?

What Is Time and Date Manipulation?

According to your program’s requirements, it may need to control, manage, or adjust the behavior or representation of times and dates.

Different programming languages have their own functions for time and date manipulation. The Go language has extensive capabilities, useful for this purpose.

Time and date manipulation can include:

  • Obtaining the current time of a location or timezone.
  • Performing arithmetic operations on times and dates.
  • Changing the input/output format of times and dates.

To start manipulating time and date in your Go applications, import the time package alongside the other packages you're using.

        import (
    "fmt"
    "time"
)

How to Get the Current Time and Date in Go

A common use case for time manipulation is obtaining the current local time or the current time of a specific timezone or location.

To get the time and date in your local time or in a specific timezone or location, you can use the time.Now() and time.LoadLocation() functions:

        func main() {
    // Get the current time and date in Local time
    myTime := ime.Now()
    fmt.Println("Current time in ", myTime.Location(), " is: ", myTime)
 
    // Another way to get local time
    location, _ := time.LoadLocation("Local") // or time.LoadLocation("")
    fmt.Println("Current time in ", location, " is: ", time.Now().In(location))
 
    // another location
    location, _ = time.LoadLocation("America/New_York")
    fmt.Println("Current time in ", location, " is: ", myTime.In(location))
 
    // get the current time in Mountain Time Zone(MST)
    location, _ = time.LoadLocation("MST")
    fmt.Println("Current time in ", location, " is: ", myTime.In(location))
}

Running the program above with go run filename.go produces the following output in the terminal:

output of Go program to get current time

The LoadLocation method doesn’t support every location and timezone abbreviation. According to the Go documentation, it only supports locations in the IANA.org database.

How to Get Separate Components From a Given Date

You can get each component of the timestamp separately which is similar to when working with time and dates in JavaScript.

There are numerous ways to accomplish this using Go's time functions. This section illustrates each method.

You can use the Date() function to get the day, month, and year, and the Clock() function to get the hour, minute, and seconds. For example:

        func main() {
    myTime := time.Now();

    year, month, day := myTime.Date()
    fmt.Println("Year :", year)
    fmt.Println("Month :", month)
    fmt.Println("Day :", day)
    
    hour, min, sec := myTime.Clock()
    fmt.Println("Hour :", hour)
    fmt.Println("Minute :", min)
    fmt.Println("Seconds :", sec)
}

The output illustrates the different parts of the timestamp:

output of code in Go to get time and date

You can also get units of the timestamp individually with the time functions for each of them:

        func main() {
    myTime := time.Now()
 
    // get each unit from Year to Nanosecond
    fmt.Println("Year :", myTime.Year())
    fmt.Println("Month :", myTime.Month())
    fmt.Println("Day :", myTime.Day())
    fmt.Println("Hour :", myTime.Hour())
    fmt.Println("Minute :", myTime.Minute())
    fmt.Println("Seconds :", myTime.Second())
    fmt.Println("Nanosecond :", myTime.Nanosecond())
}

As the output illustrates, this also gives you access to nanoseconds:

output of go program to get each time unit

The examples up to this point have focused on obtaining timestamp units from the current time. You can carry out the same kinds of action on a timestamp that isn't time.Now().

You can extract the year, month, day, hour, minute, and second of a given date. To do so, you must either initialize a new date object or parse the date from a string:

        func main() {
    // get individual components of the time from Year to Nanosecond
   // from a specific date
    yourTime := time.Date(2020, 07, 1, 06, 32, 10, 0, time.UTC)
    fmt.Println("Year :", yourTime.Year())
    fmt.Println("Month :", yourTime.Month())
    fmt.Println("Day :", yourTime.Day())
    fmt.Println("Hour :", yourTime.Hour())
    fmt.Println("Minute :", yourTime.Minute())
    fmt.Println("Seconds :", yourTime.Second())
    fmt.Println("Nanosecond :", yourTime.Nanosecond())

    // using the Clock() function to get hour, minute, and second
    yourHour, yourMin, yourSec := yourTime.Clock()
    fmt.Println("Hour :", yourHour)
    fmt.Println("Minute :", yourMin)
    fmt.Println("Seconds :", yourSec)
 
    // get time and date from string
    dateString := "2020-07-01 06:32:10"
    layout := "2006-01-02 15:04:05" // your desired output format
    yourTime, _ = time.Parse(layout, dateString)
    fmt.Println("Your time is: ", yourTime)
    fmt.Println("Year :", yourTime.Year())
    fmt.Println("Month :", yourTime.Month())
    fmt.Println("Day :", yourTime.Day())
    fmt.Println("Hour :", yourTime.Hour())
    fmt.Println("Minute :", yourTime.Minute())
    fmt.Println("Seconds :", yourTime.Second())
}

This code produces the following output:

output of code to get individual component of time

Note that Parse() uses UTC by default if you do not specify a timezone in the date string.

How to Perform Arithmetic Operations With Date and Time

Arithmetic operations are another type of manipulation you can perform on time and date in Go. Simple operations like addition, subtraction, and time difference are all possible.

Go allows you to define time.Duration values with all units of time from time.Hour to time.Nanosecond. You can use these values to add or subtract time using Add(). There is also an AddDate() function which takes in 3 parameters: years, months, and days for performing addition or subtraction.

The following code demonstrates use of these functions:

        func main() {
    curTime := time.Now()
    curTime = curTime.Add(time.Hour) // adds one hour
    fmt.Println("Current time is: ", curTime)
    tomorrow := curTime.Add(time.Hour * 24)
    fmt.Println("This time tomorrow is: ", tomorrow)
    nextWeek := curTime.Add(time.Hour * 24 * 7)
    fmt.Println("This time next week is: ", nextWeek)
 
    // using AddDate(y,m,d)
    nextTomorrow := curTime.AddDate(0, 0, 2)
    fmt.Println("This time Next tomorrow is: ", nextTomorrow)
    nextMonth := curTime.AddDate(0, 1, 0)
    fmt.Println("This time next month is: ", nextMonth)
    fiveYearsAndOneMonthAfter := curTime.AddDate(5, 1, 0)
    fmt.Println("This time five years and one month after is: ", fiveYearsAndOneMonthAfter)
}

Which produces the following output:

output of go program for time and date addition

You can also subtract time with Add() and AddDate() by passing negative parameters. For instance:

        func main() {
    curTime := time.Now()
 
    // subtract one day using AddDate()
    yesterday := curTime.AddDate(0, 0, -1)
    fmt.Println("This time yesterday was: ", yesterday)
 
    // subtract one month using Add()
    lastMonth := curTime.Add(time.Hour * -24 * 30)
    fmt.Println("This time last month was: ", lastMonth)
}

Produces this output:

output of program to subtract time and date

Although you can use Add() and AddDate() to find the distinction between dates, Go has a Sub() function which works a bit differently:

        func main() {
    curTime = time.Now()
    past := time.Date(2022, time.December, 25, 12, 0, 0, 0, time.UTC)
    diff := past.Sub(curTime)
    fmt.Println("Difference between now and the past is: ", diff)
    // get the difference in various units
    years := int(diff.Hours() / 24 / 365)
    fmt.Println("Years: ", years)
    months := int(diff.Hours() / 24 / 30)
    fmt.Println("Months: ", months)
    days := int(diff.Hours() / 24)
    fmt.Println("Days: ", days)
    hours := int(diff.Hours())
    fmt.Println("Hours: ", hours)
    // diff.Minutes(), diff.Seconds(), diff.Milliseconds(), diff.Nanoseconds() also return their units
}

This code produces the following output:

output of program to get time and date difference

How to Get Time and Date in Various Formats

You can also get time and date outputs in multiple formats using the Format() function. Here are some common formatting styles:

        func main() {
    curTime = time.Now()
    // built-in standard formatting styles
    fmt.Println("Current time is: ", curTime)
    fmt.Println("Current time in RFC3339 format is: ", curTime.Format(time.RFC3339))
    fmt.Println("Current time in RFC3339Nano format is: ", curTime.Format(time.RFC3339Nano))
    fmt.Println("Current time in RFC1123 format is: ", curTime.Format(time.RFC1123))
    fmt.Println("Current time in RFC1123Z format is: ", curTime.Format(time.RFC1123Z))
    fmt.Println("Current time in RFC822 format is: ", curTime.Format(time.RFC822))
    fmt.Println("Current time in RFC822Z format is: ", curTime.Format(time.RFC822Z))
    fmt.Println("Current time in RFC850 format is: ", curTime.Format(time.RFC850))
    fmt.Println("Current time in ANSIC format is: ", curTime.Format(time.ANSIC))
    fmt.Println("Current time in Unix format is: ", curTime.Format(time.UnixDate))
    // custom formatting styles
    // DD-MM-YYYY HH:MM:SS
    fmt.Println("Current time in custom format is: ", curTime.Format("02-01-2006 15:04:05"))
    // MM-DD-YYYY HH:MM:SS
    fmt.Println("Current time in custom format is: ", curTime.Format("01-02-2006 15:04:05"))
    // YYYY-MM-DD HH:MM:SS
    fmt.Println("Current time in custom format is: ", curTime.Format("2006-01-02 15:04:05"))
    // DD.MM.YYYY
    fmt.Println("Current time in custom format is: ", curTime.Format("02.01.2006"))
    // DD/MM/YYYY
    fmt.Println("Current time in custom format is: ", curTime.Format("02/01/2006"))
    // 01 Feb 2006
    fmt.Println("Current time in custom format is: ", curTime.Format("02 Jan 2006"))
    // 01 February 2006 Monday
    fmt.Println("Current time in custom format is: ", curTime.Format("02 February 2006 Monday"))
    // 01 February 2006 Mon 15:04:05
    fmt.Println("Current time in custom format is: ", curTime.Format("02 February 2006 Mon 15:04:05"))
}

These different types of formatting produce the following output:

output of time and date in different formats program

Manipulating Time and Date in Go

The list of manipulations that you can carry out on times and dates is almost unending. Depending on the scope of your application, you may need to perform many diverse date/time operations.

For any use case you may have, the time package is very functional and has many built-in methods.

You can use date and time manipulation to build a simple daily planner or task scheduler app.