2014-02-12 4 views
1

어떻게이 "2013-10-20 18:36:40"을 Ruby datetime으로 변환합니까?문자열 datetime을 Ruby datetime으로 변환

나는 다음과 같은 노력하고있어,하지만 작동하지 않습니다 : 시간이이를 만들고 그

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

누락 :

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

당신이 앞에있는 경우 귀하의 코드가 작동합니다 로드하고 싶지 않다면'require 'active_support/all'' (또는'active_support/core_ext/string/conversions '만 필요합니다)와 함께 모든. –

+0

Worked. 감사. – 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는 레일이 아닌 루비로 제공됩니다. –

0

DateTime#parse 방법이있다 :

2.1.0 :001 > require 'date' 
=> true 
2.1.0 :002 > DateTime.parse('2013-10-20 18:36:40') 
=> #<DateTime: 2013-10-20T18:36:40+00:00 ((2456586j,67000s,0n),+0s,2299161j)> 

레일 작업이 시간대 안전한 코드를 작성하는 것을 고려하는 경우 :

Time.zone.parse("2013-10-20 18:36:40") 

http://www.elabs.se/blog/36-working-with-time-zones-in-ruby-on-rails

관련 문제