How to add/subtract Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to a date in Go Language
Hello everyone, In this tutorial, we will learn how to add/subtract Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to date in Go Language.
The time package in Go language provides Add() function which is used to add/subtract a duration to time t. Since duration can be represented in hours, minutes, seconds, milliseconds, microseconds and nanoseconds,
The signature of the Add method is:
func (t Time) Add(d Duration) Time
Example 1: Go Program to add/subtract minutes.
package main
import (
"fmt"
"time"
)
func main() {
//Current date and time
dt1 := time.Now()
fmt.Println("Current date and time : ", dt1)
//Adding 30 minutes
dt2 := dt1.Add(30 * time.Minute)
fmt.Println("After 30 minutes:", dt2)
//Subtract 3 minutes
dt3 := dt1.Add(-3 * time.Minute)
fmt.Println("Before 3 minutes:", dt3)
}
Output:
Example 2: Go Program to add/subtract seconds.
package main
import (
"fmt"
"time"
)
func main() {
//Current date and time
dt1 := time.Now()
fmt.Println("Current date and time : ", dt1)
//Adding 120 seconds
dt2 := dt1.Add(120 * time.Second)
fmt.Println("After 120 seconds:", dt2)
//Subtract 170 seconds
dt3 := dt1.Add(-170 * time.Second)
fmt.Println("Before 170 seconds:", dt3)
}
Output:
Example 3: Go Program to add/subtract milliseconds.
package main
import (
"fmt"
"time"
)
func main() {
//Current date and time
dt1 := time.Now()
fmt.Println("Current date and time : ", dt1)
//Adding 1200 Milliseconds
dt2 := dt1.Add(1200 * time.Millisecond)
fmt.Println("After 1200 Milliseconds:", dt2)
//Subtract 1700 Milliseconds
dt3 := dt1.Add(-1700 * time.Millisecond)
fmt.Println("Before 1700 Milliseconds:", dt3)
}
Output:
Example 4: Go Program to add/subtract microseconds.
package main
import (
"fmt"
"time"
)
func main() {
//Current date and time
dt1 := time.Now()
fmt.Println("Current date and time : ", dt1)
//Adding 12000 Microseconds
dt2 := dt1.Add(12000 * time.Microsecond)
fmt.Println("After 12000 Microseconds:", dt2)
//Subtract 12000 Microseconds
dt3 := dt1.Add(-12000 * time.Microsecond)
fmt.Println("Before 12000 Microseconds:", dt3)
}
Output:
Example 5: Go Program to add/subtract nanoseconds.
package main
import (
"fmt"
"time"
)
func main() {
//Current date and time
dt1 := time.Now()
fmt.Println("Current date and time : ", dt1)
//Adding 120000 Nanoseconds
dt2 := dt1.Add(120000 * time.Nanosecond)
fmt.Println("After 120000 Nanoseconds:", dt2)
//Subtract 120000 Nanoseconds
dt3 := dt1.Add(-120000 * time.Nanosecond)
fmt.Println("Before 120000 Nanoseconds:", dt3)
}
Output: