Nital
Nital

Reputation: 6114

How to extract just the date portion from a time in Rails?

I have the following piece of code currently in my view.

display.html.erb

<% @total_sales_volume.each do |record| %>
    <%= record.transaction_date %>
<% end %>

What gets displayed currently: 2016-02-23 00:00:00 UTC

What I want to display: 2016-02-23

Upvotes: 1

Views: 136

Answers (3)

Dharam Gollapudi
Dharam Gollapudi

Reputation: 6438

You could use one of the following:

<% @total_sales_volume.each do |record| %>
    <%= record.transaction_date.strftime("%Y-%m-%d") %>
<% end %>

or

<% @total_sales_volume.each do |record| %>
    <%= record.transaction_date.to_date %>
<% end %>

Upvotes: 3

Tal Avissar
Tal Avissar

Reputation: 10314

You need to use the strftime function as follows:

<% @total_sales_volume.each do |record| %>
    <%= record.transaction_date.strftime("%Y-%m-%d") %>
<% end %>

These are the useful formats which you can specify in the strftime function:

Date (Year, Month, Day):
  %Y - Year with century (can be negative, 4 digits at least)
          -0001, 0000, 1995, 2009, 14292, etc.
  %C - year / 100 (round down.  20 in 2009)
  %y - year % 100 (00..99)

  %m - Month of the year, zero-padded (01..12)
          %_m  blank-padded ( 1..12)
          %-m  no-padded (1..12)
  %B - The full month name (``January'')
          %^B  uppercased (``JANUARY'')
  %b - The abbreviated month name (``Jan'')
          %^b  uppercased (``JAN'')
  %h - Equivalent to %b

  %d - Day of the month, zero-padded (01..31)
          %-d  no-padded (1..31)
  %e - Day of the month, blank-padded ( 1..31)

  %j - Day of the year (001..366)

Time (Hour, Minute, Second, Subsecond):
  %H - Hour of the day, 24-hour clock, zero-padded (00..23)
  %k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
  %I - Hour of the day, 12-hour clock, zero-padded (01..12)
  %l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
  %P - Meridian indicator, lowercase (``am'' or ``pm'')
  %p - Meridian indicator, uppercase (``AM'' or ``PM'')

  %M - Minute of the hour (00..59)

  %S - Second of the minute (00..59)

  %L - Millisecond of the second (000..999)
  %N - Fractional seconds digits, default is 9 digits (nanosecond)
          %3N  millisecond (3 digits)
          %6N  microsecond (6 digits)
          %9N  nanosecond (9 digits)
          %12N picosecond (12 digits)

Upvotes: 1

max
max

Reputation: 102240

You would use .strftime. The weird name is from the ancient C function which it emulates.

<% @total_sales_volume.each do |record| %>
    <%= record.transaction_date.strftime("%Y-%m-%d") %>
<% end %>

Upvotes: 0

Related Questions