ed1t
ed1t

Reputation: 8689

formatting date in ruby

I have a date in the format 05/22/2011 13:10 Eastern Time (US & Canada)

How can I convert that into a date object? This is what I used to parse the date from sting but I'm getting invalid date error.

str = "05/22/2011 13:10 Eastern Time (US & Canada)"
Date.strptime(str, "%d/%m/%Y %H:%M:%S %Z")

Upvotes: 0

Views: 282

Answers (2)

fl00r
fl00r

Reputation: 83680

Your sting: 05/22/2011 13:10 Eastern Time (US & Canada).

Here is a number of mistakes in your pattern:

  • Month is a first argument
  • Day is a second
  • Here is no any seconds in your time, only hours and minutes

Also your string includes Date and Time as well, so you'd better to use DateTime class instead of Date class:

Date.strptime(str, "%m/%d/%Y %H:%M %Z")
#=> Sun, 22 May 2011

or

DateTime.strptime(str, "%m/%d/%Y %H:%M %Z")
#=> Sun, 22 May 2011 13:10:00 -0500 

To work with datetime you should require it first:

require 'date'
dt = DateTime.strptime("05/22/2011 13:10 Eastern Time (US & Canada)", "%m/%d/%Y %H:%M %Z")
#=> #<DateTime: 353621413/144,-5/24,2299161>
dt.to_s
#=> "2011-05-22T13:10:00-05:00"
dt.hour
#=> 13
...

Upvotes: 3

Himadri Choudhury
Himadri Choudhury

Reputation: 10353

There are 2 bugs in your call to Date.strptime

1) The date and month are reversed

2) There is no seconds field in your string

Upvotes: 1

Related Questions