Customizing Time Format in Rails 5 Apps

Steps

Step 1

In products/index.html.erb:

<%= task.due_date %>

Gives the following ugly output.

task.name due on 2016-01-17

The due_date.to_s(:long) output is shown below.

task.name due on January 17, 2016

The output for :short format is shown below.

task.name due on 17 Jan

The output for :db format is shown below.

task.name due on 2016-01-17

Step 2

We can customize the time format like this:

due_date.strftime("due on %B %d at %I:%M %p")

This will lead to duplication if we need to call from different views. Let's see how we can define our own time format that will allow us to do our application specific format due_date.to_s(:due_time)

Step 3

Create config/initializers/custom_time_formats.rb file with time format customization:

Time::DATE_FORMATS[:due_time] = "due on %B %d at %I:%M %p"

Step 4

Restart server and reload tasks index page. In order to display the date as well as the time, we need to use datetime column not date. Modify the migration for adding the due_date.

class AddDueDateToTasks < ActiveRecord::Migration[5.0]
  def change
    add_column :tasks, :due_date, :datetime
  end
end

Let's populate the database with new data that has values for due_date column in tasks table.

rails db:drop
rails db:migrate
rails db:seed

The seeds.rb is same as before, since we are using ActiveSupport methods, it does not require any changes. The tasks/index.html.erb looks like this:

<tbody>
  <% @task_months.each do |month, tasks| %>
    <%= month.strftime('%B') %>
  <tr>
    <% for task in tasks %>
    <div class='task'>
        <strong>  <%= task.name %> </strong>
        <%= task.due_date.to_s(:due_time) %>
    </div>
    <% end %>
   </tr>         
  <% end %>   
</tbody>

Reload the tasks index page:

Get rich quick due on January 17 at 11:23 PM
Buy a puppy  due on January 17 at 11:23 PM
Dance in the rain due on January 17 at 11:23 PM

Summary

In this article, you learned how to customize time format in Rails 5 web apps.

References

For a Good Strf Time


Related Articles


Create your own user feedback survey