Commit cebf55dc authored by Roger Peppe's avatar Roger Peppe Committed by Russ Cox

time: new AddDate method

R=rsc
CC=golang-dev
https://golang.org/cl/5465044
parent fc6df2fd
...@@ -564,6 +564,20 @@ func (t Time) Sub(u Time) Duration { ...@@ -564,6 +564,20 @@ func (t Time) Sub(u Time) Duration {
return Duration(t.sec-u.sec)*Second + Duration(t.nsec-u.nsec) 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 ( const (
secondsPerMinute = 60 secondsPerMinute = 60
secondsPerHour = 60 * 60 secondsPerHour = 60 * 60
......
...@@ -634,6 +634,32 @@ func TestDate(t *testing.T) { ...@@ -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 { var daysInTests = []struct {
year, month, di int year, month, di int
}{ }{
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment