123
123

Reputation: 8951

Time.parse "11-21-2017 3:00PM -0500" doesn't work - Ruby/Rails

I'm trying to parse a string into a Time/DateTime object. This usually is pretty robust, but the particular format I'm working with is running into problems. I have the string "11-21-2017 3:00PM -0500" and when running Time.parse I get and argument out of range error. If I try to use something like .to_datetime, I get an error invalid date.

Is there something specifically wrong with my format, or is there something else going on here?

Upvotes: 0

Views: 134

Answers (2)

Satishakumar Awati
Satishakumar Awati

Reputation: 3790

Time.parse failing to identify format of time you are providing, better you should go ahead with using

   Time.strptime("11-21-2017 3:00PM -0500", "%m-%d-%Y %I:%M%p %z")

This accepts both time and format as arguments. For API documentation refer the link https://ruby-doc.org/stdlib-2.1.1/libdoc/time/rdoc/Time.html#method-c-strptime

I hope this helps you.

Upvotes: 2

rks
rks

Reputation: 185

I can reproduce your out of range issue.

You need to provide format of your date string.

Following code works:

DateTime.strptime("11-21-2017 3:00PM -0500", "%m-%d-%Y %I:%M%p %z")

Upvotes: 3

Related Questions