34

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).

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Kevin
  • 5,972
  • 17
  • 63
  • 87

1 Answers1

83

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
robustus
  • 3,626
  • 1
  • 26
  • 24
  • 2
    How about parsing exception? – chrisapotek Jul 25 '13 at 22:54
  • Is there a way to detect if a string will throw the parsing exception? – theUtherSide Feb 05 '16 at 21:21
  • you mean like a validator? No. Per documentation `Date.parse` doesn't even function as a validator (which is why it throws an ArgumentError instead of a more meaningful one). If you want to validate time-strings you might want to take a look at some gems that are specific to such a purpose. Timeliness might be such a gem. – robustus Feb 05 '16 at 22:28
  • is there a way to add a timezone to use with this. For example, if I do `DateTime.parse("20060224")` it returns `Fri, 24 Feb 2006 00:00:00 +0000` but i need it to be in a specific timezone such as Eastern. – Zack Herbert Feb 15 '17 at 03:12
  • Depending on where you are. In a rails environment (active_support/core_ext/date_time and active_support/core_ext/time specifically), you can do the following: `DateTime.parse('20060224').in_time_zone('EST')` – robustus Feb 15 '17 at 08:36