Rails格式化日期


126

我要向API发布日期,所需的格式如下:

2014-12-01T01:29:18

我可以从模型中获取日期,如下所示:

Model.created_at.to_s

返回:

2014-12-01 01:29:18 -0500

如何使用Rails或Ruby将其格式化为所需的T格式,并删除-0500?

Answers:


227

Model.created_at.strftime("%FT%T")

哪里,

%F - The ISO 8601 date format (%Y-%m-%d)
%T - 24-hour time (%H:%M:%S)

以下是一些您可以在方法中指定的常用格式DateTime格式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)

有关方法格式的完整列表strftime请访问APIDock


1
做得好!!我想不出静态T插入将如何工作,但是这个技巧起作用了……
HackerKarma 2014年

通用格式的快捷方式:%D-与(%m /%d /%y)相同
RajeshM 2015年

1
使用%A,如果你想在一周的某一天,例如“星期三”,或%a为“星期三”
joeytwiddle

71

试试这个:

created_at.strftime('%FT%T')

这是一个时间格式化功能,可为您提供一种表示日期的字符串表示形式的方法。(http://ruby-doc.org/core-2.2.1/Time.html#method-i-strftime)。

从APIdock:

%Y%m%d           => 20071119                  Calendar date (basic)
%F               => 2007-11-19                Calendar date (extended)
%Y-%m            => 2007-11                   Calendar date, reduced accuracy, specific month
%Y               => 2007                      Calendar date, reduced accuracy, specific year
%C               => 20                        Calendar date, reduced accuracy, specific century
%Y%j             => 2007323                   Ordinal date (basic)
%Y-%j            => 2007-323                  Ordinal date (extended)
%GW%V%u          => 2007W471                  Week date (basic)
%G-W%V-%u        => 2007-W47-1                Week date (extended)
%GW%V            => 2007W47                   Week date, reduced accuracy, specific week (basic)
%G-W%V           => 2007-W47                  Week date, reduced accuracy, specific week (extended)
%H%M%S           => 083748                    Local time (basic)
%T               => 08:37:48                  Local time (extended)
%H%M             => 0837                      Local time, reduced accuracy, specific minute (basic)
%H:%M            => 08:37                     Local time, reduced accuracy, specific minute (extended)
%H               => 08                        Local time, reduced accuracy, specific hour
%H%M%S,%L        => 083748,000                Local time with decimal fraction, comma as decimal sign (basic)
%T,%L            => 08:37:48,000              Local time with decimal fraction, comma as decimal sign (extended)
%H%M%S.%L        => 083748.000                Local time with decimal fraction, full stop as decimal sign (basic)
%T.%L            => 08:37:48.000              Local time with decimal fraction, full stop as decimal sign (extended)
%H%M%S%z         => 083748-0600               Local time and the difference from UTC (basic)
%T%:z            => 08:37:48-06:00            Local time and the difference from UTC (extended)
%Y%m%dT%H%M%S%z  => 20071119T083748-0600      Date and time of day for calendar date (basic)
%FT%T%:z         => 2007-11-19T08:37:48-06:00 Date and time of day for calendar date (extended)
%Y%jT%H%M%S%z    => 2007323T083748-0600       Date and time of day for ordinal date (basic)
%Y-%jT%T%:z      => 2007-323T08:37:48-06:00   Date and time of day for ordinal date (extended)
%GW%V%uT%H%M%S%z => 2007W471T083748-0600      Date and time of day for week date (basic)
%G-W%V-%uT%T%:z  => 2007-W47-1T08:37:48-06:00 Date and time of day for week date (extended)
%Y%m%dT%H%M      => 20071119T0837             Calendar date and local time (basic)
%FT%R            => 2007-11-19T08:37          Calendar date and local time (extended)
%Y%jT%H%MZ       => 2007323T0837Z             Ordinal date and UTC of day (basic)
%Y-%jT%RZ        => 2007-323T08:37Z           Ordinal date and UTC of day (extended)
%GW%V%uT%H%M%z   => 2007W471T0837-0600        Week date and local time and difference from UTC (basic)
%G-W%V-%uT%R%:z  => 2007-W47-1T08:37-06:00    Week date and local time and difference from UTC (extended)

31

为它创建一个初始化程序:

# config/initializers/time_formats.rb

在其中添加以下内容:

Time::DATE_FORMATS[:custom_datetime] = "%d.%m.%Y"

然后按以下方式使用它:

post.updated_at.to_s(:custom_datetime)

Your️您必须重新启动Rails服务器才能正常工作。

查看文档以获取更多信息:http : //api.rubyonrails.org/v5.1/classes/DateTime.html#method-i-to_formatted_s


1
我必须重新启动开发服务器才能使它正常工作。
阿里·哈里斯

为了配合这样的:“加上你自己的日期时间格式#to_formatted_s”(api.rubyonrails.org/classes/...
乔瓦尼Benussi的

16

由于I18n是从2.2版开始的Rails核心功能,因此可以使用其localize -method。通过应用上述的strftime%变量,您可以在config/locales/en.yml(或其他语言)下指定所需的格式,如下所示:

time:
  formats:
    default: '%FT%T'

或者,如果您想在一些特定的地方使用这种格式,可以将其称为这样的变量

time:
  formats:
    specific_format: '%FT%T'

之后,您可以像下面这样在视图中使用它:

l(Mode.last.created_at, format: :specific_format)  
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.