mirror of https://github.com/jackc/pgx.git
Make JSON output confirm to ISO8601 timestamp without a timezone
parent
52e2858629
commit
cdc672cf3f
|
@ -12,6 +12,7 @@ import (
|
|||
)
|
||||
|
||||
const pgTimestampFormat = "2006-01-02 15:04:05.999999999"
|
||||
const jsonISO8601 = "2006-01-02T15:04:05.999999999"
|
||||
|
||||
type TimestampScanner interface {
|
||||
ScanTimestamp(v Timestamp) error
|
||||
|
@ -76,7 +77,7 @@ func (ts Timestamp) MarshalJSON() ([]byte, error) {
|
|||
|
||||
switch ts.InfinityModifier {
|
||||
case Finite:
|
||||
s = ts.Time.Format(time.RFC3339Nano)
|
||||
s = ts.Time.Format(jsonISO8601)
|
||||
case Infinity:
|
||||
s = "infinity"
|
||||
case NegativeInfinity:
|
||||
|
@ -106,16 +107,15 @@ func (ts *Timestamp) UnmarshalJSON(b []byte) error {
|
|||
default:
|
||||
tss := *s
|
||||
// PostgreSQL uses ISO 8601 without timezone for to_json function and casting from a string to timestampt
|
||||
if !strings.HasSuffix(tss, "Z") {
|
||||
tss = tss + "Z"
|
||||
}
|
||||
|
||||
tim, err := time.Parse(time.RFC3339Nano, tss)
|
||||
if err != nil {
|
||||
return err
|
||||
if err == nil {
|
||||
*ts = Timestamp{Time: tim, Valid: true}
|
||||
}
|
||||
tim, err = time.Parse(jsonISO8601, tss)
|
||||
if err == nil {
|
||||
*ts = Timestamp{Time: tim, Valid: true}
|
||||
}
|
||||
|
||||
*ts = Timestamp{Time: tim, Valid: true}
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
@ -116,9 +116,9 @@ func TestTimestampMarshalJSON(t *testing.T) {
|
|||
result string
|
||||
}{
|
||||
{source: pgtype.Timestamp{}, result: "null"},
|
||||
{source: pgtype.Timestamp{Time: tm, Valid: true}, result: "\"2012-03-29T10:05:45Z\""},
|
||||
{source: pgt, result: "\"2012-03-29T10:05:45Z\""},
|
||||
{source: pgtype.Timestamp{Time: time.Date(2012, 3, 29, 10, 5, 45, 555*1000*1000, time.UTC), Valid: true}, result: "\"2012-03-29T10:05:45.555Z\""},
|
||||
{source: pgtype.Timestamp{Time: tm, Valid: true}, result: `"2012-03-29T10:05:45"`},
|
||||
{source: pgt, result: `"2012-03-29T10:05:45"`},
|
||||
{source: pgtype.Timestamp{Time: time.Date(2012, 3, 29, 10, 5, 45, 555*1000*1000, time.UTC), Valid: true}, result: `"2012-03-29T10:05:45.555"`},
|
||||
{source: pgtype.Timestamp{InfinityModifier: pgtype.Infinity, Valid: true}, result: "\"infinity\""},
|
||||
{source: pgtype.Timestamp{InfinityModifier: pgtype.NegativeInfinity, Valid: true}, result: "\"-infinity\""},
|
||||
}
|
||||
|
@ -137,6 +137,7 @@ func TestTimestampMarshalJSON(t *testing.T) {
|
|||
t2 := tsStruct
|
||||
err = json.Unmarshal(b, &t2)
|
||||
assert.NoErrorf(t, err, "failed to unmarshal %v with %s", tt.source, err)
|
||||
assert.True(t, tsStruct.TS.Time.Unix() == t2.TS.Time.Unix())
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue