Rails:Date.today 是 UTC 吗? [英] Rails: Is Date.today in UTC?

查看:52
本文介绍了Rails:Date.today 是 UTC 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中调用 Date.today 会返回当前日期.但是,它在哪个时区?我假设UTC,但我想确定.文档无论如何都不要说.

Calling Date.today in Ruby returns the current date. However, what timezone is it in? I assume UTC, but I want to make sure. The documentation doesn't state either way.

推荐答案

TL;DR: Date.today 使用系统的本地时区.如果您要求它是 UTC,则从 UTC 时间获取日期,例如Time.now.utc.to_date.

TL;DR: Date.today uses the system’s local time zone. If you require it be in UTC, instead get the date from a UTC time, e.g. Time.now.utc.to_date.

日期没有时区,因为它们不代表时间.

Dates do not have timezones, since they don't represent a time.

也就是说,至于如何计算当天,让我们看一下Date.today 的代码:

That said, as for how it calculates the current day, let's look at this extract from the code for Date.today:

time_t t;
struct tm tm;
// ...
if (time(&t) == -1)
  rb_sys_fail("time");
if (!localtime_r(&t, &tm))
  rb_sys_fail("localtime");

然后继续使用 tm 来创建 Date 对象.由于 tm 包含系统的本地时间,使用 localtime(), Date.today 因此使用系统的本地时间,而不是 UTC.

It then proceeds to use use tm to create the Date object. Since tm contains the system's local time using localtime(), Date.today therefore uses the system's local time, not UTC.

您始终可以使用 Time#utc 在任何 Time 上将其就地转换为 UTC,或 Time#getutc 返回一个新的等效 Time UTC 对象.然后你可以调用 Time#to_date 获取Date.所以:some_time.getutc.to_date.

You can always use Time#utc on any Time convert it in-place to UTC, or Time#getutc to return a new equivalent Time object in UTC. You could then call Time#to_date on that to get a Date. So: some_time.getutc.to_date.

如果您使用 ActiveSupport 的时区支持(包含在 Rails 中),请注意,它与 Ruby 的时间构造函数完全分离并且不会影响它们(即它不会改变 Time.nowDate.today 的工作方式).另请参阅Time的ActiveSupport扩展.

If you’re using ActiveSupport’s time zone support (included with Rails), note that it is completely separate from Ruby’s time constructors and does not affect them (i.e. it does not change how Time.now or Date.today work). See also ActiveSupport extensions to Time.

这篇关于Rails:Date.today 是 UTC 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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