0

I need to format a string to date:

date = DateTime.parse("05/15/2017")
formatted_date = date.strftime('%m/%d/%Y')
puts formatted_date

But I'm getting an error:

`parse': invalid date (ArgumentError)

And if I try to parse 15/05/2017 then it works.

How to parse 05/15/2017 into %m/%d/%Y format?

8
  • Specify format when parsing, obviously. Look up strptime. Commented Feb 17, 2017 at 14:59
  • Your code puzzles me. First you parse a date string, and then you turn it into a string again? What's the point? What is it that you actually want to do, parse or format? Commented Feb 17, 2017 at 15:02
  • @SergioTulentsev it's not as strange as you might think. plenty of applications have users input a date and then later display the date in a similar or the same format. i'm sure den plans to do stuff with the date other than parsing it and displaying it, but questions on stackoverflow are supposed to cut out the irrelevant code and focus on the problem. Commented Feb 17, 2017 at 15:12
  • @eiko: "cut out the irrelevant code and focus on the problem" - this one failed to do that, though. :) Or, rather, question title doesn't reflect actual content and problem. Commented Feb 17, 2017 at 15:16
  • 1
    Ruby doesn't want - funny title Commented Feb 17, 2017 at 17:33

1 Answer 1

4

It is the first line that raises the error, because Date.parse doesn't know how to handle the string "05/15/2016". Use Date.strptime instead and tell Ruby how to read the string:

DateTime.strptime('05/15/2017', '%m/%d/%Y')
#=> #<DateTime: 2017-05-15T00:00:00+00:00 ((2457889j,0s,0n),+0s,2299161j)>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Mann :) Perfect

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.