How to add N weeks to a given date in Go

1 Answer

0 votes
package main

import (
	"fmt"
	"time"
)

// AddWeeksToDate adds a specified number of weeks to a given time.Time.
// 
// @param baseDate The original time.Time value.
// @param weeks    The number of weeks to add (can also be negative to subtract).
// @return         A new time.Time with the added weeks.
func AddWeeksToDate(baseDate time.Time, weeks int) time.Time {
	// AddDate takes (years, months, days). 
	// We pass 0 years, 0 months, and weeks * 7 days to shift the calendar safely.
	return baseDate.AddDate(0, 0, weeks*7)
}

func main() {
	// Initialize a sample date: November 8, 2026 (using UTC to avoid local timezone noise)
	targetDate := time.Date(2026, time.November, 8, 12, 0, 0, 0, time.UTC)
	weeksToAdd := 4

	// Perform the addition
	resultDate := AddWeeksToDate(targetDate, weeksToAdd)

	// Display the formatted results using Go's reference time layout (2006-01-02)
	fmt.Printf("Original date:        %s\n", targetDate.Format("2006-01-02"))
	fmt.Printf("After adding %d weeks: %s\n", weeksToAdd, resultDate.Format("2006-01-02"))
}


/*
run:

Original date:        2026-11-08
After adding 4 weeks: 2026-12-06

*/

 



answered 14 hours ago by avibootz
...