Rene Chan
Rene Chan

Reputation: 985

Internationalization of local_time (Rails)

Simple question, but quite important please. I have a field in my view : @event.start_time which I applied local_time to, since the table uses UTC as a default, but users can be from anywhere.

I would like to translate the time from english to the current user's locale. as of now my field looks like <%= local_time(@event.start) %>.

I tried <%= I18n.l(local_time(@event.start), format: :long) %> and obviously it does not work, as it expects a date object, not a string.

Anybody knows how to handle please?

Thanks

Upvotes: 0

Views: 841

Answers (1)

Deepesh
Deepesh

Reputation: 6398

You can't directly use the Internationalization here, local_time gem supports it but for that you will have to supply the set of translations, for example if you check the i18n.coffee file of the gem you will find the default English translation set already added and similarly you can add for others.

Example:

LocalTime.config.i18n["es"] = {
  date: {
    dayNames: [ … ],
    monthNames: [ … ],
    …
  },
  time: {
    …
  },
  datetime: {
    …
  }
}

LocalTime.config.locale = "es"

Source: https://github.com/basecamp/local_time#configuration

The other option would be that if you have their timezone saved in your database you can convert the UTC time to particular timezone and then pass to the I18n.l which will convert the time in your required format. For this either you can set the Time.zone directly to the user's timezone or use in_time_zone method to convert UTC time to user's time. To set the Time.zone directly you can add a before_action in ApplicationController like this:

before_action :set_time_zone

def set_time_zone
  Time.zone = current_user.time_zone if current_user
end

Now whenever you will fetch the time for this particular session it will return it in the user's timezone so you will not have to convert it each time.

Upvotes: 1

Related Questions