Skip to content

Commit

Permalink
minor: add some x/jsonx.ISO8601 shortcuts
Browse files Browse the repository at this point in the history
more features designed for the past 2-3 months to come, this is just a hotfix
  • Loading branch information
kataras committed Apr 8, 2024
1 parent 1d106d8 commit 384ca4d
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
38 changes: 34 additions & 4 deletions x/jsonx/iso8601.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,14 @@ type ISO8601 time.Time
var _ Exampler = (*ISO8601)(nil)

// ParseISO8601 reads from "s" and returns the ISO8601 time.
//
// The function supports the following formats:
// - 2024-01-02T15:04:05.999999Z
// - 2024-01-02T15:04:05+07:00
// - 2024-04-08T08:05:04.830140+00:00
// - 2024-01-02T15:04:05Z
// - 2024-04-08T08:05:04.830140
// - 2024-01-02T15:04:05
func ParseISO8601(s string) (ISO8601, error) {
if s == "" || s == "null" {
return ISO8601{}, nil
Expand Down Expand Up @@ -216,10 +224,12 @@ func (t ISO8601) MarshalJSON() ([]byte, error) {
// Examples returns a list of example values.
func (t ISO8601) ListExamples() any {
return []string{
"2006-01-02T15:04:05",
"2022-08-09T00:00:00.000000",
"2022-08-10T03:21:00.000000+03:00",
"2023-02-04T09:48:14+00:00",
"2024-01-02T15:04:05.999999Z",
"2024-01-02T15:04:05+07:00",
"2024-04-08T08:05:04.830140+00:00",
"2024-01-02T15:04:05Z",
"2024-04-08T08:05:04.830140",
"2024-01-02T15:04:05",
}
}

Expand All @@ -235,6 +245,26 @@ func (t ISO8601) IsZero() bool {
return time.Time(t).IsZero()
}

// After reports whether the time instant "t" is after "u".
func (t ISO8601) After(u ISO8601) bool {
return t.ToTime().After(u.ToTime())
}

// Equal reports whether the time instant "t" is equal to "u".
func (t ISO8601) Equal(u ISO8601) bool {
return t.ToTime().Equal(u.ToTime())
}

// Add returns the time "t" with the duration added.
func (t ISO8601) Add(d time.Duration) ISO8601 {
return ISO8601(t.ToTime().Add(d))
}

// Sub returns the duration between "t" and "u".
func (t ISO8601) Sub(u ISO8601) time.Duration {
return t.ToTime().Sub(u.ToTime())
}

// String returns the text representation of the "t" using the ISO8601 time layout.
func (t ISO8601) String() string {
tt := t.ToTime()
Expand Down
6 changes: 6 additions & 0 deletions x/jsonx/iso8601_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ func TestParseISO8601(t *testing.T) {
want: ISO8601(time.Date(2024, 01, 02, 15, 04, 05, 0, time.UTC)),
wantErr: false,
},
{
name: "Timestamp with Zulu time with microseconds",
input: "2024-04-08T08:05:04.830140",
want: ISO8601(time.Date(2024, 04, 8, 8, 05, 04, 830140*1000, time.UTC)),
wantErr: false,
},
{
name: "Basic ISO8601 layout",
input: "2024-01-02T15:04:05",
Expand Down

0 comments on commit 384ca4d

Please sign in to comment.