Skip to content

timestamp: add means to convert Timestamp to & from time.Time #350

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions ptypes/timestamp/timestamp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package timestamp

import "time"

//NewTimestamp returns a Timestamp given a time.Time
//
//There will be data loss
func NewTimestamp(t time.Time) *Timestamp {
return &Timestamp{
Seconds: t.Unix(),
Nanos: int32(t.Nanosecond()),
}
}

//Time Transforms timestamp to time.Time
//
//There will be data loss
func (m *Timestamp) Time() time.Time {
return time.Unix(m.Seconds, int64(m.Nanos))
}
34 changes: 34 additions & 0 deletions ptypes/timestamp/timestamp_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package timestamp

import (
"testing"
"time"
)

func TestTimestampsConversions(t *testing.T) {

times := []time.Time{
time.Time{},
time.Date(2014, time.January, 1, 1, 1, 1, 1, time.UTC),
time.Date(2015, time.February, 2, 1, 1, 1, 1, time.UTC),
time.Date(2016, time.March, 1, 2, 1, 1, 1, time.UTC),
time.Date(2017, time.April, 1, 1, 2, 1, 1, time.UTC),
time.Date(2018, time.May, 1, 1, 1, 2, 1, time.UTC),
time.Date(2019, time.June, 1, 1, 1, 1, 2, time.UTC),
time.Date(2020, time.July, 2, 2, 2, 2, 2, time.UTC),
time.Date(2021, time.August, 2, 2, 2, 2, 2, time.UTC),
time.Date(2021, time.August, 2, 2, 2, 2, 9999999999, time.UTC),
}

for _, tc := range times {
ts := NewTimestamp(tc)
tsTime := ts.Time()

// equality can't be true but difference
// gives us approximate correctness
if tsTime.Sub(tc) != 0 {
t.Errorf("NewDuration(%s).Duration() != %[1]s. Duration: %[2]v. Diff: %s", tc, ts, tsTime.Sub(tc))
}
}

}