Customizing Time Format in Rails 5 Apps


Step 1

In products/index.html.erb:

<%= task.due_date %>

Gives the following ugly output. due on 2016-01-17

The due_date.to_s(:long) output is shown below. due on January 17, 2016

The output for :short format is shown below. due on 17 Jan

The output for :db format is shown below. 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

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:

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

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


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


For a Good Strf Time

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.