您如何以UTC而不是本地时区JSON Marshall pq.NullTime? [英] How do you JSON Marshall a pq.NullTime in UTC rather than the local timezone?

查看:42
本文介绍了您如何以UTC而不是本地时区JSON Marshall pq.NullTime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在postgres表中有日期。日期以UTC时区存储。

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

来自python的示例。

Example from python.

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

当我从go lib / pq内编组这些日期时,我的本地时区被应用了。

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
}

示例日志:

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 2018-09-07 15: 00:00 UTC。

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

您如何以UTC而不是本地时区JSON Marshall pq.NullTime?

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

推荐答案

图书馆通常使用本地时区构造 time.Time 值,但是时间仍然是相同的,因此您不必为此担心。

Libraries usually construct time.Time values using the local timezone, but the time instant is still the same, so you shouldn't worry about that.

如果您想专门在UTC区域中显示/输出时间,则您到UTC时区的时间。为此,您可以使用 Time.UTC() 方法:

If you want to display / output the time in UTC zone specifically, then "switch" your time to UTC timezone. For this, you may use the Time.UTC() method:

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

仅此而已。

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

Also note that if your NullTime is not valid, I would rather output JSON null instead of an empty string.

这篇关于您如何以UTC而不是本地时区JSON Marshall pq.NullTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆