diff --git a/proto/date.go b/proto/date.go index 39d3e0d0..3f850327 100644 --- a/proto/date.go +++ b/proto/date.go @@ -31,9 +31,10 @@ func (d Date) String() string { return d.Time().UTC().Format(DateLayout) } -// ToDate returns Date of time.Time in UTC. +// ToDate returns Date of time.Time. func ToDate(t time.Time) Date { - return Date(t.Unix() / secInDay) + _, offset := t.Zone() + return Date((t.Unix() + int64(offset)) / secInDay) } // NewDate returns the Date corresponding to year, month and day in UTC. diff --git a/proto/date32.go b/proto/date32.go index f4b25138..00ec39ce 100644 --- a/proto/date32.go +++ b/proto/date32.go @@ -26,9 +26,10 @@ func (d Date32) String() string { return d.Time().Format(DateLayout) } -// ToDate32 returns Date32 of time.Time in UTC. +// ToDate32 returns Date32 of time.Time. func ToDate32(t time.Time) Date32 { - return Date32((t.Unix() - date32Epoch) / secInDay) + _, offset := t.Zone() + return Date32((t.Unix() + int64(offset) - date32Epoch) / secInDay) } // NewDate32 returns the Date32 corresponding to year, month and day in UTC. diff --git a/proto/date32_test.go b/proto/date32_test.go index 27630c4a..d7a37ca2 100644 --- a/proto/date32_test.go +++ b/proto/date32_test.go @@ -35,6 +35,27 @@ func TestDate32_Time(t *testing.T) { }) } +func TestToDate32(t *testing.T) { + for _, tc := range []struct { + Value string + }{ + {Value: "2006-01-02T06:04:03+07:00"}, + {Value: "2008-01-02T06:44:15+03:00"}, + {Value: "2009-01-01T06:03:31+12:00"}, + {Value: "2006-12-31T22:04:41-06:30"}, + } { + t.Run(tc.Value, func(t *testing.T) { + v, err := time.Parse(time.RFC3339, tc.Value) + require.NoError(t, err) + d := ToDate32(v) + expected := NewDate32(v.Year(), v.Month(), v.Day()) + assert.Equal(t, v.Format(DateLayout), d.String()) + assert.Equal(t, expected.String(), d.String()) + assert.Equal(t, expected, d) + }) + } +} + func BenchmarkDate32_Time(b *testing.B) { b.ReportAllocs() diff --git a/proto/date_test.go b/proto/date_test.go index a92ce2d3..965c38f3 100644 --- a/proto/date_test.go +++ b/proto/date_test.go @@ -5,6 +5,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDate_Time(t *testing.T) { @@ -34,6 +35,27 @@ func TestDate_Time(t *testing.T) { }) } +func TestToDate(t *testing.T) { + for _, tc := range []struct { + Value string + }{ + {Value: "2006-01-02T06:04:03+07:00"}, + {Value: "2008-01-02T06:44:15+03:00"}, + {Value: "2009-01-01T06:03:31+12:00"}, + {Value: "2006-12-31T22:04:41-06:30"}, + } { + t.Run(tc.Value, func(t *testing.T) { + v, err := time.Parse(time.RFC3339, tc.Value) + require.NoError(t, err) + d := ToDate(v) + expected := NewDate(v.Year(), v.Month(), v.Day()) + assert.Equal(t, v.Format(DateLayout), d.String()) + assert.Equal(t, expected.String(), d.String()) + assert.Equal(t, expected, d) + }) + } +} + func BenchmarkDate_Time(b *testing.B) { b.ReportAllocs()