2012-06-18 53 views
67

了Flickr API提供了一個張貼日期作爲Unix時間戳一個使用Ruby的時間:「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.格式化on Rails的

例如,這裏是日期「1100897479」。我如何使用Ruby on Rails進行格式化?

回答

26

Easiest is to use strftime (docs)

如果是在視圖方面使用,最好將其包裝在助手中。

+1

我沒有弄清楚如何使用它。你能給我一個小例子嗎? – Alexandre

+6

my_date_variable.strftime(「%m /%d /%Y」) –

+6

strftime不是乾的。請不要將strftime分散到您的項目中。至少你提到了一個幫手,但是config/initializers/time_formats.rb對Rails來說更具慣用。 – PhilT

6

首先,您需要將時間戳轉換爲實際的Ruby日期/時間。 如果你收到它只是作爲一個字符串或Facebook的詮釋,你需要做這樣的事情:

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如其他答案概述。

+0

這段代碼拋出一個錯誤'puts Time.at('1100897479')' - 無法將字符串轉換爲精確的數字(TypeError) – Alexandre

+0

啊,它是以字符串形式到達的?確定「to_i」它確定它是一個int(上面編輯的例子包含這個) –

1

由於時間戳秒從unix新紀元,您可以使用DateTime.strptime(「字符串分析時」)與正確的說明符:

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(如果你想要日期和時間)。如果您需要不同的格式,您可以撥打DateTime#strftime(如果您對格式字符串有困難,請查看strftime.net)或使用rfc822之類的內置方法之一。

172

一旦你解析了時間戳字符串並有一個時間對象(詳見其他答案),你可以使用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" 

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

+1;一旦有日期,最簡單的解決方案,特別是如果現有的格式之一工作。 –

+0

我想甚至有一種方法可以註冊新的格式。 – CMW

+4

是的,通過初始化器中的地圖。 –

13

@ CMW的答案是爆炸的錢。我已經將此答案添加爲如何配置初始值設定項的示例,以便Date和Time對象獲得格式化

config/initializers/time_formats。RB

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

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

而且下面的兩個命令通過所有的DATE_FORMATS在當前的環境下將迭代,並顯示當天的日期和時間,每種格式:

Time::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(':- ')} 
7

看一看localize,或l

如:

l Time.at(1100897479) 
+1

這是最好的解決方案,因爲格式可能因地區而異。您還可以根據需要添加任意數量的自定義格式:請參閱http://guides.rubyonrails.org/i18n.html#adding-date-time-formats –

33

這是我的回答,

所以首先您需要將時間戳轉換爲實際的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這個小指南,以防萬一誰更喜歡。

+0

儘管此鏈接可能回答此問題,但最好包含基本部分答案在這裏,並提供參考鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 - [來自評論](/ review/low-quality-posts/10586543) –

+0

Hi @MihaiCaracostea,根據你的建議重新做了我的回答,謝謝:) – eduwass