为什么 Rails 以 UTC 存储时间? [英] Why does Rails store times in UTC?

查看:33
本文介绍了为什么 Rails 以 UTC 存储时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,Rails 将所有时间以 UTC 时间存储在数据库中.如果您将时区设置为其他时区,当您保存到数据库或从中检索时,它会在该时区和 UTC 之间自动转换.

Normally, Rails stores all times in the database in UTC time. If you set your time zone to be something else, it converts automatically between that zone and UTC when you save to the database or retrieve from it.

这种方法有哪些优点?有什么缺点吗?有没有办法让 Rails 使用不同的时区?

What are some of the advantages of this approach? Are there any disadvantages? Is there any way to have Rails use a different time zone?

认为一些优点可能是:

  • UTC 消除了季节性时间变化的歧义
  • 您可以向不同的用户显示不同的时区,同时在数据库中保持一致

我能想到的唯一缺点是,对于所有用户实际上都在同一时区的内部应用程序,这种差异使得基于本地时间运行原始 SQL 查询变得更加困难.

The only disadvantage I can think of is that, for an internal app where all users are actually in the same time zone, this difference makes it harder to run raw SQL queries based on local time.

推荐答案

这个问题有点宗教的感觉,但我会根据我的个人经验来回答.

This question has a little bit of a religious feel to it, but I'm going to answer it based on my personal experience.

始终以明确的形式存储日期.以 UTC 格式存储日期几乎是这方面的标准.

Always store dates in an unambiguous form. Storing the date in UTC is pretty much the standard in that regard.

优点:

  • 您可以对数据库中的日期时间进行简单的数学运算,而无需对其进行转换.
  • 您可以在表示层调整日期的显示
  • Web 应用程序可以使用一点 javascript 来显示本地时间

缺点:

  • 您需要将所有时间转换为显示的本地"时间
  • 本地时间 <-> UTC 转换会产生少量处理损失

你能让 Rails 做一些不同的事情吗?可能,但我从未尝试过,因为要与恕我直言是明智的设计作斗争实在是太费事了.

Can you get rails to do something different? Possibly, but I've never tried as it just was too much work to fight what IMHO was a sensible design.

从仅使用我的时区"的意义上使用 UTC 是否有意义?是的.你的服务器可能在加利福尼亚,你的用户在纽约,在这种情况下谁决定当地时间.服务器?用户?迈克,谁刚好在伦敦出差一周?在这种情况下,您使用哪个时区?

Does it make sense to use UTC from a 'just use my timezone' sense? Yes. Your server could be in California, your users in New York and who decides what is local time in that case. The server? The users? Mike, who just happens to be in London for the week on a business trip? In this case what timezone do you use?

这篇关于为什么 Rails 以 UTC 存储时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆