convert String to DateTime

2020-01-30 03:39发布

问题:

I need to parse following String into a DateTime Object:
30/Nov/2009:16:29:30 +0100

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.

回答1:

DateTime.strptime allows you to specify the format and convert a String to a DateTime.



回答2:

Shouldn't this also work?

"30/Nov/2009 16:29:30 +0100".to_datetime


回答3:

I have had success with:

require 'time'
t = Time.parse(some_string)


回答4:

I used 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.



回答5:

This will convert the string in date to datetime:

"05/05/2012".to_time


回答6:

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


回答7:

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