Convert string to datetime

Hi folks:
Can anybody tell me how to convert a string format like “20110309” to a
datetime format as “m%/d%/y%”? Thanks.

On Thu, Apr 7, 2011 at 12:12 PM, Fan J. [email protected] wrote:

“20110309”

DateTime#parse:

http://ruby-doc.org/stdlib/libdoc/date/rdoc/classes/DateTime.html#M000485

ruby-1.8.7-p334 :001 > d = “20110309”
=> “20110309”
ruby-1.8.7-p334 :002 > require ‘date’
=> true
ruby-1.8.7-p334 :003 > date = DateTime.parse d
=> #<DateTime: 4911259/2,0,2299161>
ruby-1.8.7-p334 :004 > date.to_s
=> “2011-03-09T00:00:00+00:00”

Jesus.

“Jesús Gabriel y Galán” [email protected] wrote in post
#991424:

DateTime#parse:

Or DateTime.strptime, if you want to be explicit about the format.

DateTime.strptime(“20110309”,"%Y%m%d")
=> #<DateTime: 4911259/2,0,2299161>

Brian C. wrote in post #991430:

“Jesús Gabriel y Galán” [email protected] wrote in post
#991424:

DateTime#parse:

Or DateTime.strptime, if you want to be explicit about the format.

DateTime.strptime(“20110309”,"%Y%m%d")
=> #<DateTime: 4911259/2,0,2299161>

Thanks mate, it works :slight_smile:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs