2

I am using Chronic to parse dates and it is parsing the string '8/15' as August 16, 2015.

Any ideas on how I could get Chronic to recognize 8/15 as August 15, current year?

Here is the test code:

Chronic.parse('8/15') #=> 'Sun Aug 16 12:00:00 -0400 2015'
Jamie Wright
  • 1,160
  • 10
  • 23
  • It doesn't look like this is specified in the documentation however I would try passing `:context => :past` and see if that helps is parse the string. The documentation for the parse method is located here http://chronic.rubyforge.org/classes/Chronic.html#M000001 – Devin M Aug 05 '11 at 18:23
  • No, I tried that. Did not work :( – KARASZI István Aug 05 '11 at 18:25
  • Well, you have a few options you can take to solve this. You can modify the format you are getting data in. You can try to correct this data yourself by appending a year but that will only work if the data is consistently in this format. Or you can try to find another library to parse dates. – Devin M Aug 05 '11 at 18:38
  • I can't modify the format as the format is inputed by the user. I could use regular expressions to catch this use case and add the year but that seems icky. I may have to check out other libraries. – Jamie Wright Aug 05 '11 at 18:44
  • Ah! Take a look at the DateTime class in Ruby. There is a way for you to specify your own date format for parsing. http://www.ruby-doc.org/stdlib/libdoc/date/rdoc/classes/DateTime.html#M000484 – Devin M Aug 05 '11 at 19:03
  • Why don't you add a Datepicker and you normalize the input? You won't have to deal with people not entering dates correctly... – Hock Aug 05 '11 at 19:33

2 Answers2

0

As an option:

irb(main):016:0> Chronic.parse("#{Time.now.year}/8/15")
=> 2011-08-15 12:00:00 +0300
Vasiliy Ermolovich
  • 24,459
  • 5
  • 79
  • 77
  • I will have to catch this and use regular expressions. The input is entered by the user and I can't control what is entered into the method. – Jamie Wright Aug 05 '11 at 18:46
  • I mean that the user may enter '8/15' or 'Aug. 15', etc. So I only want to add the year before the input of the regular expression says that they entered '%d/%d' – Jamie Wright Aug 07 '11 at 04:08
0

The best way to do this would be using the normal DateTime parsing provided by Ruby. As an example you can parse the date by calling:

ruby-1.9.2-p290 :001 > require 'date'
 => true 
ruby-1.9.2-p290 :002 > DateTime.strptime("8/15", "%m/%d")
 => #<DateTime: 2011-08-15T00:00:00+00:00 (4911577/2,0/1,2299161)> 
ruby-1.9.2-p290 :003 > 
Devin M
  • 9,636
  • 2
  • 33
  • 46