如何将time.time从本地时间转换为UTC时间,并映射到数据库中?

huangapple go评论71阅读模式
英文:

How to convert time.time from local to UTC while mapped to the database?

问题

我有以下示例代码。我正在使用sqlx、null.v4和Oracle数据库,其中时间以本地时间存储。我想知道是否有一种方法可以在从数据库读取时间时将本地时间转换为UTC。理想情况下,我不想在查询后进行转换,因为类型为时间的字段数量很多。

type Person struct {
    ScheduledTime null.Time `db:"Scheduled_Time" json:"scheduledTime"`
}
英文:

I have the example code below. I am using sqlx, null.v4 and oracle database where the time is stored in local time. I want to know if there is a way to convert the local time to UTC while reading the time from the database. Ideally, i do not want to do the conversion post query since the number of fields of type time are a lot.

type Person struct {

     ScheduledTime null.Time `db:"Scheduled_Time" json:"scheduledTime"`
}

答案1

得分: 1

我之前也遇到过同样的问题,你可以尝试以下方法:

  1. 在你的查询中插入 now() 函数。
  2. 使用 time.parse(format, {your dateTime string}) 函数来解析日期时间字符串,它会返回两个数据。
    例如:

    format := "2000-02-02 02:02:02"
    t, err := time.Parse(format, {yourDate})
    

如果你无法使用上述方法,你可以尝试使用 substring 函数来截取你需要的数据。

英文:

i have a same problem before so this is you can try.
> you can insert now() on your query

> time.parse(format, {your dateTime string})
they have 2 return data.
example

format := "2000-02-02 02:02:02"
t, err := time.Parse(format, {yourDate})

if you can't you can alternative with substring before and get your small data

huangapple
  • 本文由 发表于 2021年7月30日 05:17:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/68582881.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定