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?

Luka Kerr
  • 4,161
  • 7
  • 39
  • 50
Mauricio Moraes
  • 7,255
  • 5
  • 39
  • 59
  • It's not actually off by one `Date.parse('30 01 2016')` gives me `#`. Looks like it's just using the current month. – Rashmirathi Sep 30 '16 at 22:33
  • 3
    Actually, the year is only correct because it's the current year too. `Date.parse '01 01 2015'` gives me `#`. Looks like once it parses the first space it considers it invalid and uses current month/year. – Rashmirathi Sep 30 '16 at 22:41

1 Answers1

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)>
Rashmirathi
  • 1,744
  • 12
  • 10