2

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.

3 Answers3

1

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)
Shadwell
  • 34,314
  • 14
  • 94
  • 99
1

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 
satheesh
  • 11
  • 2
0

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
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • I just want while searching into the Database I want my query will convert automatically for the Local Time Zone and than It will produce the result according to that. – user3269886 Feb 11 '14 at 12:51