更改 time.Time 的时区而不重新解析

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

Change time.Time timezone without reparsing

问题

我正在处理使用错误时区解析的time.Time对象。它们在内部具有UTC时区,但原始数据来自一个内部使用Europe/Paris时区存储日期时间的遗留MySQL数据库。

我想要更改时间的内部时区,而不重新解析它。我尝试了time.In()函数,但它不能解决我的用例,因为它返回另一个时区的相同时间。

我的最终解决方案是使用https://golang.org/pkg/time/#ParseInLocation根据原始值和正确的时区重新创建日期。然而,如果能够避免这种情况,那将更好。

有什么想法吗?

谢谢。

英文:

I am dealing with time.Time objects that has been parsed with the wrong timezone. They internally have a UTC tz but the original data come from a legacy MySQL database that internally store datetimes with the timezone Europe/Paris.

I would like to change the internal timezone of the time without reparsing it. I have tried the time.In() function but it does not solve my use case because it return the same time for another timezone.

My ultimate solution would be to use https://golang.org/pkg/time/#ParseInLocation to recreate the date from the value of the original with the proper location. However if this could be avoided this would be better.

Any thoughts ?

Thanks.

答案1

得分: 0

你可以只是给它们添加一个固定的偏移量吗?

t,_ := time.Parse(...)
t = t.Add(-4 * time.Hour) // 或者任何使其正常工作的偏移量

// t 现在是正确的 UTC 时间
// In 应该工作得不那么糟糕:
localTime := t.In(myRealLocation)
英文:

Can you just Add a fixed offest to them?

t,_ := time.Parse(...)
t = t.Add(-4 * time.Hour) // or whatever offset makes it work

// t is now correct utc time
// In should work less badly:
localTime := t.In(myRealLocation)

huangapple
  • 本文由 发表于 2017年5月16日 00:23:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/43984453.html
匿名

发表评论

匿名网友

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

确定