如何在 Web 应用程序中管理时区?
我不想在我的网络应用程序中管理用户的不同时区,但我不知道从哪里开始。我必须在数据库中保存每个用户的本地时间?或者可能将其转换为 UTC 时间,保存,然后再次进行转换以显示它?或者还有其他方法吗?例如,如果我的一个用户在他的当地时间进行预约,我必须将其转换为 UTC 将其存储在我的数据库中,然后当他需要时,再次将其转换为他的当地时间并显示出来?顺便说一句,我正在使用 Django。谢谢。
I wan't to manage the different timezones of my users in my web application, but I have no idea where to start. I have to save the local time of each user in my database?, or maybe make the conversion to a UTC time, save it, and then make the conversion again to show it?, or there is another way? For example, if one of my users make an appointment in his local time, I have to convert it to UTC store it in my database, and then when he need it, convert it again to his local time an show it?? By the way, I'm using Django. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将日期/时间存储为UTC(不确定Python命令是什么)
输出日期时,将它们包装起来在获取当前用户时区首选项的辅助函数中,然后调整偏移量的时间/日期,然后从应用程序输出。
http://docs.python.org/library/time.html
http://docs.python.org/library/datetime.html
Store date/time as UTC (Not sure what the Python command for that is)
When outputting dates, wrap them in a helper function that gets the current user's time zone preference, then adjust the time/date for the offset, then output it from the application.
http://docs.python.org/library/time.html
http://docs.python.org/library/datetime.html
尝试 Django 片段UTC 日期时间字段。实际上,它拥有开箱即用所需的一切。
Try the Django snippit UTC DateTime field. It has everything you'll need right out of the box, practically.
是的,即使您只有一个本地时区,您通常也应该将日期作为 UTC 时间戳存储在数据库中,并在 Web 应用程序的输入和输出阶段将其与适当时区的文本进行相互转换。当您存储了每个用户的时区后,就可以轻松地将默认时区切换为自定义时区。
pytz 是选择和转换时区的常用解决方案。 (尽管我个人也破解了自己的不那么压倒性的时区集合。)
Yes, even if you only have one local timezone, you should generally be storing your dates as UTC timestamps in the database, and converting it to and from text in the appropriate timezone in your webapps input and output stages. When you have a per-user timezone stored it's then easy to switch out the default timezone for the customised one.
pytz is the usual solution for selecting and converting timezones. (Although personally I hacked up my own less overwhelming collection of timezones.)
在我看来,使用单个“数据库时间”时区是最好的选择,因为: -
所以,是的。将用户的时区存储在数据库中,然后将所有时间存储在公共时间(如 UTC)中。当用户查看任何内容(包括时间)时转换它们。这是最简单的解决方案,它不仅仅强制所有用户假装位于同一时区。
Using a single "database time" timezone is, IMO, the best options because:-
So, yes. Store the user's timezone in the database, then store all times in a common time (Like UTC). Convert them when the user views anything including time. It's the simplest solution that doesn't just force all users to pretend to be in the same timezone.