doukougua7873 2018-09-26 07:07
浏览 32
已采纳

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

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?

  • 写回答

1条回答 默认 最新

  • douhuai4155 2018-09-26 07:45
    关注

    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.

    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"))
    

    That's all.

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集