Chloe
Chloe

Reputation: 26274

How does Rails know my timezone?

How does Rails know my time zone? I don't have it set in application.rb:

# config.time_zone = 'Central Time (US & Canada)'

I searched the whole app for time_zone and that is the only instance of it. I don't see any environment variables for time zone set either. I'm on Windows.

C:\Users\Chloe\workspace\MyBestBody>rails runner "p Time.now"
DL is deprecated, please use Fiddle
2015-06-12 23:38:33 -0400

It prints UTC time when deployed to Heroku.

C:\Users\Chloe\workspace\MyBestBody>heroku run rails console
Running `rails console` attached to terminal... up, run.1949
Loading production environment (Rails 4.2.1)
irb(main):001:0> Time.new
=> 2015-06-13 03:28:34 +0000

Rails 4.2.1

Upvotes: 0

Views: 1206

Answers (2)

Frederick Cheung
Frederick Cheung

Reputation: 84132

Your question involves two separate things.

The first is what ruby thinks the time zone is. This is the zone used when you use things likeTime.now or Time.mktime. Ruby uses the C level APIs provided by the operating system to get this information (the TZ environment variable can override this on unixy operating systems).

The second is the time zone your users will see when they use your app. This is frequently not the same thing. Even if your users were all in the same timezone it's a good idea to have your servers use UTC because it is free from things like daylight savings time.

For this reason rails has its own timezone system and the setting you found controls the default value of that timezone. Sometimes you might overwrite this on a per user basis. Rails always records information in UTC, but it will be displayed in views using the value of Time.zone (And input from forms is interpreted in that zone). You can see what the current time in this zone is by doing

Time.zone.now

Upvotes: 2

hd1
hd1

Reputation: 34677

From gettimeofday(), or so the ruby MRI source would have me believe:

int __cdecl
gettimeofday(struct timeval *tv, struct timezone *tz)
{
     FILETIME ft;

     GetSystemTimeAsFileTime(&ft);
     filetime_to_timeval(&ft, tv);

     return 0;
}

Per comment, this is a C function, called by the ruby date routines under the hood. You do not call the method yourself, rather you call the ruby methods you are calling.

Upvotes: 2

Related Questions