How to add/subtract days, months or years to a date in Go Language

Hello everyone, In this tutorial, we will learn how to add/subtract days, months or years to a date in Go Language.

The time package in Go language provides AddDate() function which is used to add/subtract years, months and days to time t. 

The signature of the AddDate method is:
func (t Time) AddDate(years int, months int, days int) Time


Example 1: Go Program to add/subtract days.

package main

import (
"fmt"
"time"
)

func main() {

//Current date and time
dt1 := time.Now()
fmt.Println("Current date and time : ", dt1)

//Adding 3 days
dt2 := dt1.AddDate(0, 0, 3)
fmt.Println("After three days: ", dt2)

//Subtract 400 days
dt3 := dt1.AddDate(0, 0, -400)
fmt.Println("Before 400 days: ", dt3)
}
Output:



Example 2: Go Program to add/subtract months.

package main

import (
"fmt"
"time"
)

func main() {

//Current date and time
dt1 := time.Now()
fmt.Println("Current date and time : ", dt1)

//Adding 3 months
dt2 := dt1.AddDate(0, 3, 0)
fmt.Println("After three months: ", dt2)

//Subtract 9 months
dt3 := dt1.AddDate(0, -9, 0)
fmt.Println("Before 9 months: ", dt3)
}
Output:



Example 3: Go Program to add/subtract years.

package main

import (
"fmt"
"time"
)

func main() {

//Current date and time
dt1 := time.Now()
fmt.Println("Current date and time : ", dt1)

//Adding 2 years
dt2 := dt1.AddDate(2, 0, 0)
fmt.Println("After two years: ", dt2)

//Subtract 7 years
dt3 := dt1.AddDate(-7, 0, 0)
fmt.Println("Before 7 years: ", dt3)
}
Output:

Author name: joy

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example