使用Ruby on Rails格式化日期

Ale*_*dre 72 ruby ruby-on-rails

flickr api提供了一个发布日期作为unix时间戳一:" The posted date is always passed around as a unix timestamp, which is an unsigned integer specifying the number of seconds since Jan 1st 1970 GMT."

例如,这是日期' 1100897479'.如何使用Ruby on Rails格式化它?

CMW*_*CMW 184

解析时间戳字符串并具有时间对象(有关详细信息,请参阅其他答案)后,可以使用Rails中的Time.to_formatted_s.它有几种内置格式,您可以使用符号指定.

引用:

time = Time.now                     # => Thu Jan 18 06:10:17 CST 2007

time.to_formatted_s(:time)          # => "06:10"
time.to_s(:time)                    # => "06:10"

time.to_formatted_s(:db)            # => "2007-01-18 06:10:17"
time.to_formatted_s(:number)        # => "20070118061017"
time.to_formatted_s(:short)         # => "18 Jan 06:10"
time.to_formatted_s(:long)          # => "January 18, 2007 06:10"
time.to_formatted_s(:long_ordinal)  # => "January 18th, 2007 06:10"
time.to_formatted_s(:rfc822)        # => "Thu, 18 Jan 2007 06:10:17 -0600"
Run Code Online (Sandbox Code Playgroud)

(Time.to_s是别名)

您也可以定义自己的格式 - 通常在初始化程序中(感谢Dave Newton指出这一点).这就是它的完成方式:

# config/initializers/time_formats.rb
Time::DATE_FORMATS[:month_and_year] = "%B %Y"
Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
Run Code Online (Sandbox Code Playgroud)

  • 是的,通过初始化器中的地图. (4认同)
  • 请注意,Time :: DATE_FORMATS不会传递给rails Date对象.对于Date对象,请使用Date :: DATE_FORMATS (3认同)
  • 关于这一点有几点说明。1) 您可以从控制台运行 Time::DATE_FORMATS 和 Date::DATE_FORMATS 来查看可用的格式(例如::short、:long 等)以及它们的定义方式。2) 使用 :default 将设置自动应用的默认格式。因此,在 time_formats.rb 初始值设定项中放置 Time:: DATE_FORMATS[:default] = "....您的自定义格式..." 并不罕见。最后,@MarkKramer,您可以通过查找 strftime 来查看可接受的日期格式指令的列表。Ruby 仅使用标准 Unix 日期格式语法。 (2认同)

Edu*_*ass 39

这是我回答这个问题,

首先,您需要将时间戳转换为实际的Ruby日期/时间.如果您从Facebook收到它作为字符串或int,您将需要执行以下操作:

my_date = Time.at(timestamp_from_facebook.to_i)
Run Code Online (Sandbox Code Playgroud)

好的,现在假设你已经有了你的约会对象......

to_formatted_s是一个方便的Ruby函数,可以将日期转换为格式化字符串.

以下是其用法的一些示例:

time = Time.now                     # => Thu Jan 18 06:10:17 CST 2007    

time.to_formatted_s(:time)          # => "06:10"
time.to_s(:time)                    # => "06:10"    

time.to_formatted_s(:db)            # => "2007-01-18 06:10:17"
time.to_formatted_s(:number)        # => "20070118061017"
time.to_formatted_s(:short)         # => "18 Jan 06:10"
time.to_formatted_s(:long)          # => "January 18, 2007 06:10"
time.to_formatted_s(:long_ordinal)  # => "January 18th, 2007 06:10"
time.to_formatted_s(:rfc822)        # => "Thu, 18 Jan 2007 06:10:17 -0600"
Run Code Online (Sandbox Code Playgroud)

如您所见:: db,:number,:short ...是自定义日期格式.

要添加自己的自定义格式,可以创建此文件:config/initializers/time_formats.rb并在其中添加自己的格式,例如:

Date::DATE_FORMATS[:month_day_comma_year] = "%B %e, %Y" # January 28, 2015
Run Code Online (Sandbox Code Playgroud)

其中:month_day_comma_year是您的格式名称(您可以将其更改为您想要的任何名称),以及%B%e,%Y是unix日期格式.

这是关于unix日期语法的快速备忘单,因此您可以快速设置自定义格式:

From http://linux.die.net/man/3/strftime    

  %a - The abbreviated weekday name (``Sun'')
  %A - The  full  weekday  name (``Sunday'')
  %b - The abbreviated month name (``Jan'')
  %B - The  full  month  name (``January'')
  %c - The preferred local date and time representation
  %d - Day of the month (01..31)
  %e - Day of the month without leading 0 (1..31) 
  %g - Year in YY (00-99)
  %H - Hour of the day, 24-hour clock (00..23)
  %I - Hour of the day, 12-hour clock (01..12)
  %j - Day of the year (001..366)
  %m - Month of the year (01..12)
  %M - Minute of the hour (00..59)
  %p - Meridian indicator (``AM''  or  ``PM'')
  %S - Second of the minute (00..60)
  %U - Week  number  of the current year,
          starting with the first Sunday as the first
          day of the first week (00..53)
  %W - Week  number  of the current year,
          starting with the first Monday as the first
          day of the first week (00..53)
  %w - Day of the week (Sunday is 0, 0..6)
  %x - Preferred representation for the date alone, no time
  %X - Preferred representation for the time alone, no date
  %y - Year without a century (00..99)
  %Y - Year with century
  %Z - Time zone name
  %% - Literal ``%'' character    

   t = Time.now
   t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 04/09/2003"
   t.strftime("at %I:%M%p")            #=> "at 08:56AM"
Run Code Online (Sandbox Code Playgroud)

希望这能帮到你.我也为这个小指南做了一个github要点,以防万一有人喜欢.


Dav*_*ton 27

最简单的是使用strftime(docs).

如果它是在视图端使用,最好将其包装在帮助器中.

  • strftime不是DRY.请不要在整个项目中分散strftime.至少你提到过一个帮助器,但是`config/initializers/time_formats.rb`对于Rails更为惯用. (7认同)
  • my_date_variable.strftime( "%米/%d /%Y") (6认同)

Reg*_*ieB 16

@ CMW的答案就是钱.我已添加此答案作为如何配置初始化程序以使Date和Time对象都获得格式的示例

配置/初始化/ time_formats.rb

date_formats = {
  concise: '%d-%b-%Y' # 13-Jan-2014
}

Time::DATE_FORMATS.merge! date_formats
Date::DATE_FORMATS.merge! date_formats
Run Code Online (Sandbox Code Playgroud)

此外,以下两个命令将遍历DATE_FORMATS当前环境中的所有命令,并以每种格式显示今天的日期和时间:

Date::DATE_FORMATS.keys.each{|k| puts [k,Date.today.to_s(k)].join(':- ')}
Time::DATE_FORMATS.keys.each{|k| puts [k,Time.now.to_s(k)].join(':- ')}
Run Code Online (Sandbox Code Playgroud)


Ben*_*ier 8

看看localize,或l

例如:

l Time.at(1100897479)
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的解决方案,因为格式可能会因地区而异。您还可以根据需要添加任意数量的自定义格式:请参见http://guides.rubyonrails.org/i18n.html#adding-date-time-formats (2认同)

Tar*_*ast 6

首先,您需要将时间戳转换为实际的Ruby日期/时间.如果您从Facebook收到它作为字符串或int,您将需要执行以下操作:

my_date = Time.at(timestamp_from_facebook.to_i)
Run Code Online (Sandbox Code Playgroud)

然后在视图中很好地格式化它,您可以使用to_s(对于默认格式):

<%= my_date.to_s %>
Run Code Online (Sandbox Code Playgroud)

请注意,如果您不放置to_s,如果您在视图或字符串中使用它,它仍将默认调用,例如以下内容也将调用to_s日期:

<%= "Here is a date: #{my_date}" %>
Run Code Online (Sandbox Code Playgroud)

或者如果您希望以特定方式格式化日期(例如使用"d/m/Y") - 您可以strftime按照其他答案中的说明使用.