首页 > 解决方案 > How do you JSON Marshall a pq.NullTime in UTC rather than the local timezone?

问题描述

I have dates in postgres table. The dates are stored with a UTC timezone.

Example from python.

roster = Roster.objects.get(id=266438)
roster.start_timestamp
Out[11]: datetime.datetime(2018, 9, 7, 15, 0, tzinfo=<UTC>)

When I marshall these dates from within go lib/pq my local time zone is somehow being applied.

func (nt *pq.NullTime) MarshalJSON() ([]byte, error) {
    if !nt.Valid {
        return []byte("\"\""), nil
    }
    val := fmt.Sprintf("\"%s\"", nt.Time.Format("01/02/2006 15:04:05"))
    fmt.Println("Marshalling FMPDateTime", nt, val)
    return []byte(val), nil
}

Example log:

Marshalling DateTime &{2018-09-08 00:30:00 +0930 ACST true} "09/08/2018 00:30:00"

2018-09-08 00:30:00 +0930 ACST is 2018-09-07 15:00:00 UTC.

How do you JSON Marshall a pq.NullTime in UTC rather than the local timezone?

标签: postgresqlgo

解决方案


库通常time.Time使用本地时区构造值,但时间瞬间仍然相同,因此您不必担心。

如果您想专门显示/输出 UTC 时区的时间,则将您的时间“切换”到 UTC 时区。为此,您可以使用以下Time.UTC()方法:

val := fmt.Sprintf("\"%s\"", nt.Time.UTC().Format("01/02/2006 15:04:05"))

就这样。

另请注意,如果您NullTime的无效,我宁愿输出 JSONnull而不是空字符串。


推荐阅读