flickr API提供了一个发布日期作为unix timestamp one:“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格式化它?
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"
7条答案
按热度按时间rjzwgtxy1#
一旦解析了时间戳字符串并拥有了一个time对象(有关详细信息,请参阅其他答案),就可以使用Rails中的Time.to_formatted_s,它内置了几种格式,可以用符号指定。
引用:
(Time.to_s是别名)
你也可以定义你自己的格式--通常是在初始化器中(感谢Dave Newton指出这一点)。
cbjzeqam2#
我来回答这个问题,
所以首先你需要把时间戳转换成一个真实的Ruby日期/时间,如果你从facebook收到的只是一个字符串或int,你需要做如下的事情:
好了,现在假设你已经有了约会对象......
**to_formatted_s**是一个方便的Ruby函数,可以将日期转换为格式化字符串。
下面是它的一些用法示例:
如您所见::db、:number、:short...是自定义日期格式。
要添加自己的自定义格式,可以创建以下文件:config/initializers/time_formats.rb并在其中添加您自己的格式,例如以下格式:
其中**:month_day_comma_year是格式的名称(您可以将其更改为任何您想要的名称),而%B %e,%Y**是unix日期格式。
这里有一个关于unix日期语法的快速备忘单,所以你可以快速设置你的自定义格式:
希望这对你有帮助。我还把这个小指南做了一个github gist,以防有人喜欢。
h4cxqtbf3#
Easiest is to use
strftime
(docs).但是,如果要在视图侧使用它,最好将其 Package 在helper中。
72qzrwbm4#
@CMW的答案是正确的,我添加这个答案是作为一个例子,说明如何配置一个初始化器,以便Date和Time对象都获得格式
配置/初始化器/时间格式.rb
另外,下面两个命令将遍历当前环境中的所有
DATE_FORMATS
,并以每种格式显示今天的日期和时间:piztneat5#
请查看
localize
或l
例如:
nszi6y056#
首先你需要把时间戳转换成一个真实的Ruby日期/时间,如果你从facebook收到的只是一个字符串或int,你需要做如下的事情:
然后,为了在视图中很好地格式化它,您可以使用
to_s
(默认格式):请注意,如果您不放置
to_s
,那么在视图或字符串中使用它时,默认情况下仍然会调用它。例如,以下代码也会在日期上调用to_s
:或者如果你想用一种特定的方式来格式化日期(例如使用“d/m/Y”)-你可以使用
strftime
,就像另一个答案中概述的那样。46scxncf7#
由于时间戳是从UNIX纪元开始的秒数,您可以使用DateTime.strptime(“字符串解析时间”)和正确的说明符:
请注意,必须使用
require 'date'
才能使其正常工作,然后可以将其称为Date.strptime
(如果只关心日期)或DateTime.strptime
(如果您想要日期和时间)。如果您需要不同的格式,您可以在其上调用DateTime#strftime(如果您很难处理格式字符串,请查看strftime.net)或使用rfc822
等内置方法之一。