How to add N weeks to the current date in Go

1 Answer

0 votes
package main

import (
	"fmt"
	"time"
)

/**
 * Adds a specified number of weeks to the current system date.
 *
 * @param weeks The number of weeks to add (supports negative numbers to subtract).
 * @return time.Time The resulting future date.
 */
func AddWeeksToCurrentDate(weeks int) time.Time {
	// 1. Get the current local time
	now := time.Now()

	// 2. Add weeks by converting them to days (1 week = 7 days) 
	// and using AddDate to handle month/year boundaries safely.
	return now.AddDate(0, 0, weeks * 7)
}

func main() {
	weeksToAdd := 4

	// Calculate the future date
	futureDate := AddWeeksToCurrentDate(weeksToAdd)

	// Format the output as YYYY-MM-DD using Go's reference time format ("2006-01-02")
	fmt.Printf("Adding %d weeks to today's date gives: %s\n", weeksToAdd, futureDate.Format("2006-01-02"))
}


/*
run:

Adding 4 weeks to today's date gives: 2026-12-06

*/

 



answered 22 hours ago by avibootz
...