doukougua7873
2018-09-26 07:07
浏览 31

您如何以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.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题