[英]Convert string datetime to Ruby datetime
How do I convert this "2013-10-20 18:36:40" into a Ruby datetime? 如何将“ 2013-10-20 18:36:40”转换为Ruby日期时间?
I'm trying the following, but it's not working: 我正在尝试以下操作,但不起作用:
"2013-10-20 18:36:40".to_datetime
That's making it this and missing the time: 做到这一点并浪费时间:
2013-10-20 00:00:00 UTC
Use DateTime::strptime
: 使用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)>
You can do the following if rails is installed on your system:-- 如果系统上安装了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
There is also DateTime#parse
method: 还有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)>
If your work with rails consider writing timezone-safe code: 如果您使用Rails,请考虑编写时区安全代码:
Time.zone.parse("2013-10-20 18:36:40")
http://www.elabs.se/blog/36-working-with-time-zones-in-ruby-on-rails http://www.elabs.se/blog/36-working-with-time-zones-in-ruby-on-rails
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.