1

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
1
  • 1
    Your code will work if you precede it with require 'active_support/all' (or just require 'active_support/core_ext/string/conversions') if you don't want to load it all. Commented Feb 12, 2014 at 3:29

3 Answers 3

4

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)>
Sign up to request clarification or add additional context in comments.

Comments

0

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 

1 Comment

active_support is available in rails, not in ruby.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.