Ruby on Rails - Localizing time in a Traditional Rails app with Moment.js - ruby on rails tutorial - rails guides - rails tutorial - ruby rails
- In Ruby, a moment in time is typically represented as a Time object.
- In a Twitter-like app, for example, the time of each tweet would be coded as a Time.
- Internally, objects of this type represent moments in time as the number of seconds since the UNIX Epoch (January 1, 1970 at midnight, UTC).
- The use of Coordinated Universal Time (UTC)
- gives us a standard to measure time against.
Controller:
View:
- Our poor user is going to have to mentally convert UTC to their local time
- What we really need to do is localize these times for the user.
- While it's possible to do this within Rails, there's a better solution.
- The browser is already aware of the user's timezone! Browser-side time localization libraries work most naturally with a browser-centric app, but it's still easy to retrofit one onto our traditional Rails app to convert UTC times to local times.
Localizing Time with Moment.js:
- we include Moment.js in our project via the momentjs-rails gem, declare a class on each string we want to convert, and use Moment to replace each string.
- Tada! Compare that with the original version above.
- The lll format specifies a human-readable form of the date at level-3 verbosity using short words, hence the three lowercase "L".
Standardizing User Input to UTC:
- The flip side is that we need to convert user input (presumably local time) into UTC for storage.
- For the sake of the example, let's assume that a user can specify the time of a bark
- When we submit this form, the time is stored in the database as if the user had entered it in UTC: Wed, 03 Feb 2016 12:00:00 UTC +00:00
- We need to convert according to our assumption that the user has entered a local time.
- With this commit, we'll add a hidden field as the "real" bark time, and use a handler on the submit event of our form to grab the user-supplied value, convert it, and set the UTC time on the hidden field.
View:
JavaScript:
- This time the database has: Wed, 03 Feb 2016 17:00:00 UTC +00:00
ruby on rails tutorial tags - ruby , rail , ruby on rails , rail forum , ruby on rails tutorial , ruby tutorial , rails guides , rails tutorial , learn ruby
Bonus: Local Language and Format:
- Moment.js also has optional support for fully localizing times with languages and formats; all you need to do is require each Moment.js locale that you want to make available.