user2270029
user2270029

Reputation: 871

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

Upvotes: 1

Views: 111

Answers (3)

trushkevich
trushkevich

Reputation: 2677

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

Upvotes: 0

Alok Anand
Alok Anand

Reputation: 3356

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 

Upvotes: 0

falsetru
falsetru

Reputation: 369474

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

Upvotes: 4

Related Questions