简体   繁体   中英

Convert string datetime to Ruby datetime

How do I convert this "2013-10-20 18:36:40" into a Ruby datetime?

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 :

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:--

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:

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM