登录
首页 >  Golang >  Go问答

将已有 time.Time 对象增加时区信息

来源:stackoverflow

时间:2024-02-28 16:54:25 175浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《将已有 time.Time 对象增加时区信息》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

假设我有以下内容:

  • postgres 数据库中具有 timestamp 列的表。
  • 数据库时区设置为 utc 以外的时间。
  • 一些使用 current_timestampnow() 插入时间戳值的 sql 语句

如 postgres 文档中所述:

current_timestamp() 函数返回一个带有时区的 timestamp,表示事务开始的日期和时间。

因此,以下语句会默默地将本地时间戳转换为绝对时间戳:

insert into foo (id, timestamp_column) values (0, current_timestamp);

假设 go 程序将此数据读入 time.time 对象,该对象将有一个空的 location

fmt.println(timefromdb.location().string() == "") // true

被解释为 utc。此时我确实知道 go 时间 timefromdb 实际上不是 utc,而且我也知道数据库时区设置是什么。

如何在该时间对象中设置正确的时区?在实践中:

// before
fmt.Println(timeFromDb)            // 2009-11-10 10:00:00
fmt.Println(timeFromDb.Location()) // 
fmt.Println(timeFromDb.UTC())      // 2009-11-10 10:00:00

// magic?

// after
fmt.Println(timeFromDb)            // 2009-11-10 10:00:00
fmt.Println(timeFromDb.Location()) // America/Vancouver
fmt.Println(timeFromDb.UTC())      // 2009-11-10 18:00:00

解决方案


你可以重新解释它:

loc,_:=time.LoadLocation("America/Vancouver")
t2:=timeFromDb.In(loc)
_,off:=t2.Zone()
theTime:=t2.Add(-time.Duration(off)*time.Second)

您还可以进行一些字符串操作,但我怀疑这更快。

理论要掌握,实操不能落!以上关于《将已有 time.Time 对象增加时区信息》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>