From: Roger Peppe Date: Thu, 15 Dec 2011 16:23:01 +0000 (-0500) Subject: time: new AddDate method X-Git-Tag: weekly.2011-12-22~187 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=cebf55dc9b2bf6b298f60cf3bffb4ad7a4583f05;p=gostls13.git time: new AddDate method R=rsc CC=golang-dev https://golang.org/cl/5465044 --- diff --git a/src/pkg/time/time.go b/src/pkg/time/time.go index e58099676f..8e24daeff7 100644 --- a/src/pkg/time/time.go +++ b/src/pkg/time/time.go @@ -564,6 +564,20 @@ func (t Time) Sub(u Time) Duration { return Duration(t.sec-u.sec)*Second + Duration(t.nsec-u.nsec) } +// AddDate returns the time corresponding to adding the +// given number of years, months, and days to t. +// For example, AddDate(-1, 2, 3) applied to January 1, 2011 +// returns March 4, 2010. +// +// AddDate normalizes its result in the same way that Date does, +// so, for example, adding one month to October 31 yields +// December 1, the normalized form for November 31. +func (t Time) AddDate(years int, months int, days int) Time { + year, month, day := t.Date() + hour, min, sec := t.Clock() + return Date(year+years, month+Month(months), day+days, hour, min, sec, int(t.nsec), t.loc) +} + const ( secondsPerMinute = 60 secondsPerHour = 60 * 60 diff --git a/src/pkg/time/time_test.go b/src/pkg/time/time_test.go index 2a22e7b274..bcc9c42365 100644 --- a/src/pkg/time/time_test.go +++ b/src/pkg/time/time_test.go @@ -634,6 +634,32 @@ func TestDate(t *testing.T) { } } +// Several ways of getting from +// Fri Nov 18 7:56:35 PST 2011 +// to +// Thu Mar 19 7:56:35 PST 2016 +var addDateTests = []struct { + years, months, days int +}{ + {4, 4, 1}, + {3, 16, 1}, + {3, 15, 30}, + {5, -6, -18 - 30 - 12}, +} + +func TestAddDate(t *testing.T) { + t0 := Date(2011, 11, 18, 7, 56, 35, 0, UTC) + t1 := Date(2016, 3, 19, 7, 56, 35, 0, UTC) + for _, at := range addDateTests { + time := t0.AddDate(at.years, at.months, at.days) + if !time.Equal(t1) { + t.Errorf("AddDate(%d, %d, %d) = %v, want %v", + at.years, at.months, at.days, + time, t1) + } + } +} + var daysInTests = []struct { year, month, di int }{