28

I have a date (Which is actually parsed from a PDF) and it could be any of the following format:

MM/DD/YYYY
MM/DD/YY
M/D/YY
October 15, 2007
Oct 15, 2007 

Is there any gem or function available in rails or ruby to parse my date? Or I need to parse it using regex?

BTW I'm using ruby on rails 3.2.

Sachin Prasad
  • 5,038
  • 12
  • 49
  • 91

2 Answers2

68

You can try Date.parse(date_string).

You might also use Date#strptime if you need a specific format:

> Date.strptime("10/15/2013", "%m/%d/%Y")
=> Tue, 15 Oct 2013

For a general solution:

format_str = "%m/%d/" + (date_str =~ /\d{4}/ ? "%Y" : "%y")
date = Date.parse(date_str) rescue Date.strptime(date_str, format_str)
Baldrick
  • 22,401
  • 6
  • 67
  • 75
Chris Heald
  • 56,837
  • 7
  • 110
  • 130
  • I can't use strptime as I don't know the format of my date :( – Sachin Prasad Jul 10 '13 at 05:38
  • You could infer it easily enough, no? If it won't parse with `Date.parse`, then split("/").last will be either 2 or 4 characters, letting you know if you should be using %y or %Y. – Chris Heald Jul 10 '13 at 05:39
  • So what your method is doing is that If it can't parse american format it will simply give it to strptime.I think it will work let me test it. – Sachin Prasad Jul 10 '13 at 05:45
  • Correct. There are a few ways to do that; mine is sloppy-but-effective. :) – Chris Heald Jul 10 '13 at 05:45
  • Most of the time my date will be in american format and if the date is less than 12 Date.parse will parse it considering it as a month.How about Date.strptime(date_str, format_str) rescue Date.parse(date_str) ? – Sachin Prasad Jul 10 '13 at 05:59
  • Worth a shot. Find what works for you - between those two methods, though, you should be able to handle all of those date formats. – Chris Heald Jul 10 '13 at 06:07
  • I have tested after reversing(Date.strptime(date_str, format_str) rescue Date.parse(date_str)) and its working great. Most of the dates I have ,It can parse it.And thanks a lot for the help please edit your answer and I will accept it. – Sachin Prasad Jul 10 '13 at 06:10
7

I find the chronic gem very easy to use for time parsing and it should work for you. i tried the examples you gave.

https://github.com/mojombo/chronic

beanie
  • 1,268
  • 8
  • 14
  • Seems to be good for handling complex dates, is there any option where I can specify that my dates coming will be in MM/DD/YYYY format and not DD/MM/YYYY format? – Sachin Prasad Jul 10 '13 at 06:31
  • 1
    this should be the default, but you can set the endianness like this `endian_precedence: :little` and it will parse DD/MM/YYYY – beanie Jul 10 '13 at 07:59