]> Cypherpunks repositories - gostls13.git/commitdiff
time: new AddDate method
authorRoger Peppe <rogpeppe@gmail.com>
Thu, 15 Dec 2011 16:23:01 +0000 (11:23 -0500)
committerRuss Cox <rsc@golang.org>
Thu, 15 Dec 2011 16:23:01 +0000 (11:23 -0500)
R=rsc
CC=golang-dev
https://golang.org/cl/5465044

src/pkg/time/time.go
src/pkg/time/time_test.go

index e58099676f07b02f500a729f3ce094b821fdefd5..8e24daeff73d309a2c2436c1ebf499c487e83ebf 100644 (file)
@@ -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
index 2a22e7b2746350ae861ca4152a30665d488a6cd4..bcc9c42365d153401a4f83633afbd37b28c7542e 100644 (file)
@@ -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
 }{