這是我的回答,
所以首先您需要將時間戳轉換爲實際的Ruby日期/時間。如果你收到它只是作爲一個字符串或來自Facebook的詮釋,你需要做這樣的事情:
my_date = Time.at(timestamp_from_facebook.to_i)
好了,現在假設你已經擁有你的約會對象......
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"
正如你所看到的::分貝,:號,:短 ...是定製的日期格式。
要添加自己的自定義格式,您可以創建這個文件:配置/初始化/ time_formats.rb,並添加您自己的格式存在,比如這裏有一個:
Date::DATE_FORMATS[:month_day_comma_year] = "%B %e, %Y" # January 28, 2015
其中:month_day_comma_year是您的格式名稱(您可以將其更改爲任何您想要的內容),並且其中的格式爲unix日期格式。
下面是在UNIX日期語法快速的cheatsheet,使您可以快速設置您的自定義格式:
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 gist這個小指南,以防萬一誰更喜歡。
我沒有弄清楚如何使用它。你能給我一個小例子嗎? – Alexandre
my_date_variable.strftime(「%m /%d /%Y」) –
strftime不是乾的。請不要將strftime分散到您的項目中。至少你提到了一個幫手,但是config/initializers/time_formats.rb對Rails來說更具慣用。 – PhilT