Friday, June 3, 2011

Javascript nonsense

I came across this issue today.
Check these:

maDate = new Date('2011-07-01');
maDate.add(18, 'months');
maDate.strftime('%d/%m/%Y'); // => 01/01/2012



maDate = new Date('2011-07-01');
maDate.setMonth(maDate.getMonth() + 18);
maDate.strftime('%d/%m/%Y'); // => 01/01/2013


Seriously?? If anyone can give an explanation about why two native javascript Date-Object methods give a different result with one of them being Date + 6 months instead of Date + 18 months, I'd be glad to read it.

Clem

4 comments:

Kluzter Benavides said...

stiesse
does that happen when the month is not july?.

maybe when you set month 25(7+18) it's trying to add those 2 years to the current date :S

Unknown said...

with this calculus it only happens with july for some very strange reason... Also, note that 'new Date()' doesn't work on IE7

Thomas Voisin said...

I think maDate.add can only add 1-12 month. when you give a number >12 it will add your number modulo 12.

18 modulo 12 = 6
=> 2011-01-01

maDate.setMonth should work like this, not maDate.add.
Are you sure that it's not
maDate.add => 01/01/2013
maDate.setMonth => 01/01/2012
??

Unknown said...

well for all I know, the "add" method is not really documented, I don't know where it comes from but anyway it's buggy so I would advise against its use. It's a shame because I liked the way it looked.
It does look like it does a modulo 12 on months which doesn't make sense because when anyone means "now + 18 months" they don't really mean "now + 6" ;)