如何将此“2013-10-20 18:36:40”转换为Ruby日期时间?
我正在尝试以下方法,但它无效:
"2013-10-20 18:36:40".to_datetime
这就是这样,错过了时间:
2013-10-20 00:00:00 UTC
答案 0 :(得分:4)
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)>
答案 1 :(得分:0)
如果您的系统上安装了rails,则可以执行以下操作: -
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 :(得分: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)>
如果您使用rails工作,请考虑编写时区安全代码:
Time.zone.parse("2013-10-20 18:36:40")
http://www.elabs.se/blog/36-working-with-time-zones-in-ruby-on-rails