How to show Time.now based on TimeZone - Rails 4 - ruby-on-rails

Hey guys i am trying to show server time but instead it shows local time. Is it possible to set server timezone to something like canada?
i tried this in application.rb
config.time_zone = 'Central Time (US & Canada)'
but when i use Time.now it shows local time.
Would appreciate your help.

Time.now will always print your system local time. If you want to print current time according to zone, then use:
Time.zone.now
Or,
Time.now.in_time_zone(Central Time (US & Canada))

Just use Time.current. Quote from its docs:
Time.current returns Time.zone.now when Time.zone or config.time_zone are set, otherwise just returns Time.now.

Related

Rails 4 - how to set a timezone for strftime?

Every user in our database can select his/her own timezone. The default timezone of our application Eastern Time:
config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = 'Eastern Time (US & Canada)'
When I display some dates/times in the application, I usually use for that purpose .strftime. How can I give a parameter to strftime to display the date/time properly (in the given timezone for the specific user)?
Or is there a better way than to format every date/time with using strftime?
EDIT:
Every user has a time_zone string column, where is stored the timezone like this: "Eastern Time (US & Canada)".
As the every date/time will be re-calculated for every timezone, how about the performance? Will this not slow down too much rendering views?
Set your time object in_time_zone() before strftime.
Say you're displaying created_at, you'd do:
object.created_at.in_time_zone(current_user.timezone).strftime("...")

How to set the timezone to EST throughout the rails app?

I want to use EST throughout the app. I have set the
config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = 'Eastern Time (US & Canada)'
what I want is, I have to get all the time I have used like "DateTime.now" and it now returns time in my local timezone but I want it to return date time in EST. Also I have date time range picker and I get the start date and end date and parse the string to time using
(params[:start_date]).to_time
which also returns the date time in local zone and instead i want all those to return in EST. How can I do this? Any help is appreciated.
Thanks in advance.
DateTime.now and Time.now doesn't respect Time.zone and will always use the server time. If the machine you're using is set to a different timezone, these 2 will use that timezone.
to_time on the other hand defaults to local timezone as mentioned in apidock (although just tried this out and I get utc by default). To get these times in the timezone set, append in_time_zone
DateTime.now.in_time_zone
Time.now.in_time_zone
string.to_time.in_time_zone
There are some shortcuts for these though. The following code will return the timestamps in the current timezone
Time.zone.now
Time.zone.parse(string)
Normally, in database date-time would be saved in UTC format unless you have selected a specific TimeZone for Active Record and it would be easier if you have to meddle with multiple TimeZones. But, while you access the values you will get the values in you selected TimeZone.
config.time_zone = 'Eastern Time (US & Canada)
Now, suppose you have a datetime value in UTC from table as
datetime1 = "2014-08-25 10:25:57 +0000"
You can convert it to the selected timezone 'Eastern Time (US & Canada)' as below,
Time.zone.parse(datetime1) => Mon, 25 Aug 2014 06:25:57 EDT -04:00
Then, if you need it in a proper format, use method strftime.
Time.zone.parse("2014-08-25 10:25:57 +0000").strftime("%d-%m-%Y %H:%M:%S") => "25-08-2014 06:25:57"
Hoep it helps :)

Rails 4 - Want To Have Rails Use My Local Time Zone for created_at & updated_at

Is there actually a way to have Rails add/update rows with created_at and update_at using the current time zone as set on my server?
I have seen many Stack Overflow solutions where people stated how to display it on a Rails view with a selected time zone.
I have also found other Stack Overflow solutions stating that it should take the time zone from my server and update created_at and updated_at. This is not true at least for the Mac Mini Server I'm running on. I have it set to my local time zone. I also have config.time_zone = 'Central Time (US & Canada)' set in config/application.rb.
I want to be able to look at the raw database data in pgAdmin3 or some kind of database backup and know when records have been created in my time zone.
Any help would be appreciated. I will keep looking.
If you want to set the db timezone and you are using ActiveRecord, then add the following in your application config:
config.active_record.default_timezone = :local
This will use your sever's timezone on the database.
# application.rb:
class Application < Rails::Application
config.time_zone = 'Eastern Time (US & Canada)'
end
Time.zone # => #<TimeZone:0x514834...>
Time.zone.name # => "Eastern Time (US & Canada)"
Time.zone.now # => Sun, 18 May 2008 14:30:44 EDT -04:00
Please refer following link >>http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html#method-c-5B-5D
You can also run rake time:zones:all in order to list all time zones Rails knows. You can then update your setting in application.rb accordingly.

Rails and dates, are they stored in UTC by default?

What is the best way for me to handle dates and timezones in rails?
Scenerio: I have customers who purchase products on a website from all over the world, and when they log in they will be able to choose which timezone they are from.
So I believe I should be storing everything in the database at UTC, and then on the front-end I should be converting the dates to the users set timezone preference.
Are their any gotchas with Ruby and Rails and datetimes etc?
I'm new to rails, so I am looking for guidance on how to handle this properly.
Fortunately Rails will pretty much handle things for you. As others pointed out, dates are stored by AR in UTC format. If you have a time_zone field for your users table you can do something like this:
# application.rb
config.time_zone = "Mountain Time (US & Canada)" # Default time zone
-
# application_controller.rb
before_filter :set_time_zone, :if => :logged_in?
protected
def set_time_zone
Time.zone = current_user.time_zone if current_user.time_zone
end
All the datetimes should be shown in the proper time zone in your views.
I have had one production app that didn't like using the default time zone, but I can't remember which version of Rails/Ruby it was running.
Ok so take a look at your config/application.rb file.
You should find commented lines:
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
So default is UTC but you can set whatever ou need there.
Yes, they are. In app, whenever you display date or time for user, everything you need is just adding timezone offset (for example: date + 1.hour for GMT+1). Remember that you need to take care of daylight saving, too. For efficency, consider adding 2 columns in your user table: timezone and time_offset. Then you would on each case do something like
= #order.created_at + session[:user].time_offset
Instead of always checking offset for each timezone set in profile.
I found
rake time:zones:all
to be really useful. It shows a list of offsets and then zone name strings under that. eg:
* UTC +12:00 *
Auckland
Fiji
Kamchatka
Magadan
Marshall Is.
Solomon Is.
Wellington
I needed below in application.rb (not intuitive given default time zone string of "Mountain Time (US & Canada)"):
config.time_zone = 'Wellington'

Time.now & Created_at are different? Ruby on Rails

My site is deployed on heroku. Time.now will return today, but the created_at field of a record (created right now) will say its tomorrow. I assume this has to do with server time?
Is there a way to make sure they're the same?
Best,
Elliot
Update so I did this "heroku rake time:zones:us"
it gave me:
* UTC -10:00 *
Hawaii
* UTC -09:00 *
Alaska
* UTC -08:00 *
Pacific Time (US & Canada)
* UTC -07:00 *
Arizona
Mountain Time (US & Canada)
* UTC -06:00 *
Central Time (US & Canada)
* UTC -05:00 *
Eastern Time (US & Canada)
Indiana (East)
however, when I set config.time_zone = 'UTC -05:00' in my environment, the app fails to start. any ideas?
Rails always stores UTC time on the database; the created_at field by itself should be offset by exactly your timezone's variation relative to UTC.
Whenever you load a record in your application, the fields get converted to the timezone specified in environment.rb. It might have something like this:
config.time_zone = 'UTC'
For the time to be converted properly to your timezone, you might change this configuration setting to one matching your actual time zone. For instance:
config.time_zone = 'Central Time (US & Canada)'
To see available zones, issue "rake -D time" on your rails directory. This will give you instructions on how to get time zone names for use in configuration.
To add onto Roadmaster's answer, I had a similar challenge: the normal Rails timestamps were stored based on UTC in the database, but I needed to query to find all records created today according to the local time zone.
The query looked like this:
completions.where("created_at BETWEEN ? AND ?",
Date.today, Date.today + 1.day).count >= 1
I fixed this by calling #to_time on the dates, as follows. This converted them into a timestamp having the proper time zone, and the correct records were fetched in the database, effectively making the query timezone-aware.
completions.where("created_at BETWEEN ? AND ?",
Date.today.to_time, Date.today.to_time + 1.day).count >= 1
Just need to uncomment and change to the time zone you wanna.
If you want to check all the time zone, run rake time:zones:all and will output a list.
config/Application.rb
module Clerk
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'La Paz'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
end
end
I added the following to lines of code. I wanted the created_at to be on the ActiveRecord data creation.
config/Application.rb
module RailsApp
class Application < Rails::Application
config.time_zone = 'Pacific Time (US & Canada)'
config.active_record.default_timezone = 'Pacific Time (US & Canada)'
end
end

Resources