Date.today在UTC? [英] Is Date.today in UTC?

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

问题描述

在Ruby中调用 Date.today 返回当前日期。但是,哪个时区呢?我假设UTC,但我想确定。 文档没有

解决方案

日期没有时区,因为它们不代表时间。这就是说,对于 它计算当前的日期,我们来看看这个从 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。






您可以随时使用 Time#utc 在任何时间将其原位转换为UTC,或 Time#getutc 返回新的等价物时间对象在UTC。然后,您可以致电 Time#to_date ,以获得日期。所以: some_time.getutc.to_date



如果你使用ActiveSupport的时区支持(包含在Rails中),请注意,它与Ruby的时间构造函数完全不同,并不影响它们(即不会更改如何 Time.now Date.today 工作)。另请参阅 ActiveSupport扩展程序时间


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.

解决方案

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

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");

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.


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.

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.

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

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