使用 RubyonRails 格式化日期

Flickr api 以 unix 时间戳1提供发布的日期: “ 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 格式化它?

136745 次浏览

最简单的方法是使用 strftime(docs)

但是,如果它是在视图端使用的,那么最好将它包装在一个 helper 中。

首先,您需要将时间戳转换为实际的 Ruby Date/Time。 如果你只是从 facebook 上收到一个字符串或者 int,你需要这样做:

my_date = Time.at(timestamp_from_facebook.to_i)

然后,要在视图中很好地格式化它,只需使用 to_s(默认格式) :

<%= my_date.to_s %>

注意,如果你没有放入 to_s,在默认情况下,如果你在视图或字符串中使用它,它仍然会被调用。例如,下面的代码也会在日期调用 to_s:

<%= "Here is a date: #{my_date}" %>

或者如果你想用特定的方式格式化日期(例如使用“ d/m/Y”)——你可以使用另一个答案中概述的 strftime

由于时间戳以 UNIX 时代以来的秒为单位,因此可以使用 日期时间 strptime(“ string parse time”)和正确的说明符:

Date.strptime('1100897479', '%s')
#=> #<Date: 2004-11-19 ((2453329j,0s,0n),+0s,2299161j)>
Date.strptime('1100897479', '%s').to_s
#=> "2004-11-19"
DateTime.strptime('1100897479', '%s')
#=> #<DateTime: 2004-11-19T20:51:19+00:00 ((2453329j,75079s,0n),+0s,2299161j)>
DateTime.strptime('1100897479', '%s').to_s
#=> "2004-11-19T20:51:19+00:00"

请注意,您必须使用 require 'date'才能正常工作,然后您可以将其称为 Date.strptime(如果您只关心日期)或 DateTime.strptime(如果您想要日期和时间)。如果需要不同的格式,可以调用 日期时间 # strftime(如果格式字符串很难处理,可以查看 Strftime.net) ,或者使用 rfc822这样的内置方法。

一旦解析了时间戳字符串并有了一个 time 对象(详细信息请参阅其他答案) ,就可以使用 Rails 中的 To _ format _ 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"

(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}") }

@ CMW 的回答是,钱来得正是时候。我添加了这个答案作为一个示例,说明如何配置初始值设定项,以便 Date 和 Time 对象都获得格式设置

Config/initializer/time _ format. rb

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


Time::DATE_FORMATS.merge! date_formats
Date::DATE_FORMATS.merge! date_formats

下面的两个命令将遍历当前环境中的所有 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(':- ')}

看看 localize或者 l

例如:

l Time.at(1100897479)

这是我回答这个问题的方法,

因此,首先需要将时间戳转换为实际的 Ruby Date/Time。如果你只是从 facebook 上收到一个字符串或者 int,你需要这样做:

my_date = Time.at(timestamp_from_facebook.to_i)

现在假设你已经有了约会对象。

To _ format _ 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"

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

要添加您自己的自定义格式,您可以创建这个文件: Config/initializer/time _ format. rb并在那里添加您自己的格式,例如:

Date::DATE_FORMATS[:month_day_comma_year] = "%B %e, %Y" # January 28, 2015

其中 : 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"

希望这对你有帮助。 我还做了一个 Github 要点的小指南,如果有人喜欢的话。