Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a date in rails

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.

like image 672
Sachin Prasad Avatar asked Jul 10 '13 05:07

Sachin Prasad


People also ask

How do you parse a date in Ruby?

Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.

What is DateTime parse?

The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.

What is parsing in Ruby?

Parsing is the art of making sense of a bunch of strings and converting them into something we can understand. You could use regular expressions, but they are not always suitable for the job. For example, it is common knowledge that parsing HTML with regular expressions is probably not a good idea.

What is Strftime Ruby?

Ruby | Time strftime() function Time#strftime() is a Time class method which returns the time format according to the directives in the given format string. Syntax: Time.strftime() Parameter: Time values. Return: time format according to the directives in the given format string.


2 Answers

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) 
like image 179
Chris Heald Avatar answered Sep 29 '22 11:09

Chris Heald


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

like image 36
beanie Avatar answered Sep 29 '22 09:09

beanie