How to Use time.Time.Add() Function in Golang

Golang time.Time.Add() Function is “used to add the stated time and duration.”

Syntax

func (t Time) Add(d Duration) Time

Parameters

  1. d: It is the duration that is to be added to the time stated.
  2. t: It is the stated time.

Return value

It returns the result of adding stated t and d.

Example 1: How to Use time.Time.Add() function

package main

import (
  "fmt"
  "time"
)

func main() {
  // Declaring time in UTC
  t := time.Date(2023, 7, 1, 12, 0, 0, 0, time.UTC)

  // Declaring durations
  d1 := t.Add(time.Second * 30)
  d2 := t.Add(time.Minute * 10)
  d3 := t.Add(time.Hour * 3)
  d4 := t.Add(time.Hour * 24 * 14)

  // Prints output
  fmt.Printf("Original time: %v\n", t)
  fmt.Printf("After adding 30 seconds: %v\n", d1)
  fmt.Printf("After adding 10 minutes: %v\n", d2)
  fmt.Printf("After adding 3 hours: %v\n", d3)
  fmt.Printf("After adding 14 days: %v\n", d4)
}

Output

Original time: 2023-07-01 12:00:00 +0000 UTC
After adding 30 seconds: 2023-07-01 12:00:30 +0000 UTC
After adding 10 minutes: 2023-07-01 12:10:00 +0000 UTC
After adding 3 hours: 2023-07-01 15:00:00 +0000 UTC
After adding 14 days: 2023-07-15 12:00:00 +0000 UTC

Example 2: Get the time 2 hours from now

package main

import (
  "fmt"
  "time"
)

func main() {
  // Get the current time
  now := time.Now()

  // Get the time 2 hours from now
  twoHoursLater := now.Add(2 * time.Hour)

  fmt.Println("Current Time:", now)
  fmt.Println("Two Hours Later:", twoHoursLater)
}

Output

Current Time: 2023-07-01 19:14:08.827812 +0530 IST m=+0.000230584
Two Hours Later: 2023-07-01 21:14:08.827812 +0530 IST m=+7200.000230584

That’s it.

Leave a Comment