如何从Rails中提取日期部分?

时间:2016-03-07 20:23:29

标签: ruby-on-rails ruby

我目前在视图中有以下代码。

display.html.erb

2016-02-23 00:00:00 UTC

目前显示的内容:2016-02-23

我想要显示的内容:componentDidMount

3 个答案:

答案 0 :(得分:3)

您可以使用以下其中一项:

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

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

答案 1 :(得分:1)

您需要使用strftime函数,如下所示:

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

这些是您可以在strftime函数中指定的有用格式:

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)

答案 2 :(得分:0)

您将使用.strftime。奇怪的名字来自它模仿的古代C函数。

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