I need to parse following String into a DateTime Object:
Is there an easy way to do this?
PS: I want to convert the string above as is. The colon after the year is not a typo. I also want to solve the problem with Ruby and not RoR.
DateTime.strptime allows you to specify the format and convert a String to a DateTime.
Shouldn’t this also work?
"30/Nov/2009 16:29:30 +0100".to_datetime
I have had success with:
require 'time' t = Time.parse(some_string)
Time.parse("02/07/1988"), like some of the other posters.
An interesting gotcha was that
Time was loaded by default when I opened up IRB, but
Time.parse was not defined. I had to
require 'time' to get it to work.
That’s with Ruby 2.2.
This will convert the string in date to datetime:
in Ruby 1.8, the ParseDate module will convert this and many other date/time formats. However, it does not deal gracefully with the colon between the year and the hour. Assuming that colon is a typo and is actually a space, then:
#!/usr/bin/ruby1.8 require 'parsedate' s = "30/Nov/2009 16:29:30 +0100" p Time.mktime(*ParseDate.parsedate(s)) # => Mon Nov 30 16:29:30 -0700 2009
For chinese Rails developers:
DateTime.strptime('2012-12-09 00:01:36', '%Y-%m-%d %H:%M:%S') => Sun, 09 Dec 2012 00:01:36 +0000