如何在客户端处理BST和GMT时区?将它们存储在数据库中作为UTC时间。

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

How to handle BST and GMT timezones on client side? Storing them in a DB as UTC

问题

我有一个Go应用程序,我将所有的日期时间都存储为UTC:

dateTime, err := time.Parse("2006-01-02T15:04:05.000Z", myDateTime)

这将变成类似于:2022-09-29T19:40:36.150Z

现在我想在客户端(网站上)显示这个日期时间,但要以用户所在时区的时间显示。

由于所有时间都是UTC,我可以让用户从一个时区列表中选择他们的时区,比如这个列表:https://gist.github.com/valo/c07f8db33d223f57a4cc9c670e1b6050。

然后,只需要从UTC中添加/减去一些时间,并显示出来。

但问题是夏令时,当夏季到来时,客户端的时区会发生变化,当冬季到来时又会发生变化。

人们是如何解决这个问题的?

英文:

I've got a Go app and I store all datetimes as UTC:

dateTime, err := time.Parse("2006-01-02T15:04:05.000Z", myDateTime)

This becomes something like: 2022-09-29T19:40:36.150Z.

Now I want to show this datetime client side (on a website), but showing the user the time in their timezone.

Since it's all UTC I could have the user pick their timezone from a list, like this one https://gist.github.com/valo/c07f8db33d223f57a4cc9c670e1b6050.

Then it's just a matter of adding/subtracting some time from the UTC and showing it.

But the problem is with daylight savings time, the client side timezone would have to change when it's summer, and change again when it's winter.

How are people doing this?

答案1

得分: 3

通常,这是在客户端上发生的。关于客户端时区的信息存储在浏览器中,并且如果需要,可以提供给您。但是,有一些函数可以自动解决这个问题,比如 toLocaleDateString

步骤1:
将时间字符串 2022-09-29T19:40:36.150Z 解析为 JavaScript 中的 Date 对象。

步骤2:
在日期上使用 toLocaleDateString。这将以客户端浏览器中存储的时区设置显示日期。

toLocaleDateString 的 MDN 文档

英文:

Usually, this happens on the client side. Information about the client's timezone is stored on the browser and is available to you if you need it. However, there are functions that sort this out automatically like toLocaleDateString.

Step 1.
Parse the time string 2022-09-29T19:40:36.150Z to a Date object in javascript

Step 2.
Use toLocaleDateString on the date. This will display the Date in the client's timezone setting stored in the browser

MDN docs for toLocaleDateString()

huangapple
  • 本文由 发表于 2022年9月28日 04:30:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/73873499.html
匿名

发表评论

匿名网友

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

确定