Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse Date string in Ruby

Tags:

ruby

ruby-1.8

I have a String 20120119 which represents a date in the format 'YYYYMMDD'.

I want to parse this string into a Ruby object that represents a Date so that I can do some basic date calculation, such as diff against today's date.

I am using version 1.8.6 (requirement).

like image 485
Kevin Avatar asked Jul 23 '12 17:07

Kevin


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.

How do I change the date format in Ruby?

DateTime. strptime('2001-02-03T04:05:06+07:00', '%Y-%m-%dT%H:%M:%S%z') #=> #<DateTime: 2001-02-03T04:05:06+07:00 ...> DateTime. strptime('03-02-2001 04:05:06 PM', '%d-%m-%Y %I:%M:%S %p') #=> #<DateTime: 2001-02-03T16:05:06+00:00 ...>

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.


1 Answers

You could use the Date.strptime method provided in Ruby's Standard Library:

require 'date' string = "20120723" date = Date.strptime(string,"%Y%m%d") 

Alternately, as suggested in the comments, you could use Date.parse, because the heuristics work correctly in this case:

require 'date' string = "20120723" date = Date.parse(string) 

Both will raise an ArgumentError if the date is not valid:

require 'date' Date.strptime('2012-March', '%Y-%m') #=> ArgumentError: invalid date  Date.parse('2012-Foo') # Note that '2012-March' would actually work here #=> ArgumentError: invalid date 

If you also want to represent hours, minutes, and so on, you should look at DateTime. DateTime also provides a parse method which works like the parse method on Date. The same goes for strptime.

like image 94
robustus Avatar answered Oct 01 '22 23:10

robustus