2014-02-12 245 views
1

如何將此「2013-10-20 18:36:40」轉換爲Ruby日期時間?將字符串日期時間轉換爲Ruby日期時間

我嘗試以下,但它不工作:

"2013-10-20 18:36:40".to_datetime 

這使得它這一點,缺少時間:

2013-10-20 00:00:00 UTC 
+1

如果你在它之前你的代碼將工作與'require'active_support/all''(或只是'require'active_support/core_ext/string/conversions''),如果你不想加載這一切。 –

+0

工作。謝謝。 – user2270029

回答

4

使用DateTime::strptime

require 'date' 
DateTime.strptime("2013-10-20 18:36:40", "%Y-%m-%d %H:%M:%S") 
#<DateTime: 2013-10-20T18:36:40+00:00 ((2456586j,67000s,0n),+0s,2299161j)> 
0

你如果您的系統上安裝了導軌,可以執行以下操作: -

require 'active_support/core_ext/string/conversions' 

"2013-10-20 18:36:40".to_time 



1.9.2p320 :001 > require 'active_support/core_ext/string/conversions' 
=> true 
1.9.2p320 :003 > "2013-10-20 18:36:40".to_time 
=> 2013-10-20 18:36:40 UTC 
+2

active_support在rails中可用,而不是在ruby中。 –

相關問題