user3269886
user3269886

Reputation: 47

Timezone in MySql and Rails

In my application I am storing records in the database in the UTC format. I just want that while displaying those records at the user end The result will search according to the user's time zone. Means while firing the query I just want the record should be search in according to the User's Timezone.

Upvotes: 2

Views: 156

Answers (3)

satheesh
satheesh

Reputation: 11

To show the different time depending on the user browser time.you can grab their browser time(local time)through javascript code and store it into cookie.Then set the time to rails timezone.

Make sure that you have installed jquery.cookie

 var browser_time = new Date();
 $j.cookie('time_zone', browser_time.getTimezoneOffset())

Add the before filter to set the rails timezone

 before_filter :set_timezone 

 def set_timezone
  if !request.cookies["time_zone"].blank?
   min = request.cookies["time_zone"].to_i
   Time.zone = ActiveSupport::TimeZone[-min.minutes]
  end
 end 

Upvotes: 1

Shadwell
Shadwell

Reputation: 34774

To show a different time depending on the user you need to grab their locale from somewhere. There are a few options for this (they might set it in their profile, you might have a different URL for different languages or you might be able to get it from their session). There is a lot more information in the rails internationalization guide section on setting the locale.

Basically you need to set I18n.locale to be the locale for the user. This is the example from the guide for application_controller.rb (assuming you have a locale parameter):

before_action :set_locale

def set_locale
  I18n.locale = params[:locale] || I18n.default_locale
end

Then, once you have the locale for the user you need to localize your display of the time. Again, there's more information in the guide but basically you need to call the helper method localize (aliased as l too):

localize(Time.now)

or

l(Time.now)

Upvotes: 1

Richard Peck
Richard Peck

Reputation: 76774

I think you can set the TimeZone through your app's config options:

How to change default timezone for Active Record in Rails?

#config/application.rb
config.time_zone = 'London'
config.active_record.default_timezone = :local

Upvotes: 0

Related Questions