Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

ruby - Is Date.today in 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.

question from:https://stackoverflow.com/questions/10219670/is-date-today-in-utc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...