Skip to content

proposal: time: add time.AddMonth to add a month without normalization #52775

@ousloob

Description

@ousloob

While the time.AddDate is mathematically correct with the normalization results. The need to add/substract a month in date without nomalization is there in several areas.

func (t Time) AddMonth(months int) Time

AddMonth returns the time corresponding to adding the given number of months, increment/decrement years if needed and set days to t by staying in the range days of the month added, without normalize the result.

Example:

start := time.Date(2022, 10, 31, 0, 0, 0, 0, time.UTC)
oneMonthLater := start.AddMonth(1)
threeMonthLater := start.AddMonth(3)

fmt.Printf("oneMonthLater: start.AddMonth(1) = %v\n", oneMonthLater)
fmt.Printf("threeMonthLater: start.AddMonth(3) = %v\n", threeMonthLater)

// Output:
oneMonthLater: start.AddMonth(1) = 2022-11-30 00:00:00 +0000 UTC
threeMonthLater: start.AddMonth(3) = 2023-01-31 00:00:00 +0000 UTC

Same if we reduce the date by one month.
Example:

start := time.Date(2022, 03, 31, 0, 0, 0, 0, time.UTC)
oneMonthBefore := start.AddMonth(-1)

fmt.Printf("oneMonthBefore: start.AddMonth(-1) = %v\n", oneMonthBefore)

// Output:
oneMonthBefore: start.AddMonth(-1) = 2022-02-28 00:00:00 +0000 UTC

// The results should be the same for march 30, march 29 and march 28 for non leap year.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions