3

Just got this today with my ruby console:

$ irb
2.3.1 :001 > require 'date'
 => true 
2.3.1 :002 > Date.parse '30/08/2016'
 => #<Date: 2016-08-30 ((2457631j,0s,0n),+0s,2299161j)> 
2.3.1 :003 > Date.parse '30 08 2016'
 => #<Date: 2016-09-30 ((2457662j,0s,0n),+0s,2299161j)> 
2.3.1 :004 > 

Separating with spaces (dates were formatted like this on a spreadsheet from work...dont ask why..hehe), it gave me a date one month after!!

What am I missing? Or shouldn't I expect a correct date, because I'm passing an invalid format anyway?

2
  • It's not actually off by one Date.parse('30 01 2016') gives me #<Date: 2016-09-30 ((2457662j,0s,0n),+0s,2299161j)>. Looks like it's just using the current month. Sep 30, 2016 at 22:33
  • 3
    Actually, the year is only correct because it's the current year too. Date.parse '01 01 2015' gives me #<Date: 2016-09-01 ((2457633j,0s,0n),+0s,2299161j)>. Looks like once it parses the first space it considers it invalid and uses current month/year. Sep 30, 2016 at 22:41

1 Answer 1

2

Use Date.strptime instead, it can take a template to parse the input

i.e.

Date.strptime('30 08 2016', '%d %m %Y')
=> #<Date: 2016-08-30 ((2457631j,0s,0n),+0s,2299161j)>

Just re-iterating my comments, it looks like Date.parse ignores the input after first space and just uses current month and year.

Date.parse '01 01 2015'
=> #<Date: 2016-10-01 ((2457663j,0s,0n),+0s,2299161j)>

Funnily enough spaces are fine if you spell the month.

 Date.parse '01 jan 2015' 
 => #<Date: 2015-01-01 ((2457024j,0s,0n),+0s,2299161j)>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.