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 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝