Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bizarre javascript arithmetic behavior (yup... to be expected)

ok, I'm writing a little code snippet to get the ISO date-format value for yesterday.

code:

var dateString = new Date();

var yesterday = dateString.getFullYear();

    yesterday += "-"+dateString.getMonth()+1;

    yesterday += "-"+dateString.getDate()-1;

The above code outputs 2009-111-23. It is clearly not treating dateString.getMonth() as an intiger and tacking 1 on to the end of it.

Does putting the "-"+ in front of dateString.getDate() cast getDate() into a string?

this works gets the desired result.

var dateString = new Date();

var yesterday = dateString.getFullYear() + "-";

    yesterday += dateString.getMonth()+1+ "-";

    yesterday += dateString.getDate()-1;
//yesterday = 2009-12-22

Although I don't really like the way it looks... whatever no big deal.

Can anyone explain to me why javascript acts like this? is there any explanation for why this happens?

like image 905
Derek Adair Avatar asked Dec 02 '22 06:12

Derek Adair


2 Answers

This is about associativity. + operator is left-associative, so

"-"+dateString.getMonth() + 1

is same as

("-"+dateString.getMonth()) + 1

Put parenthesis around the expression you want to be evaluated first:

"-" + (dateString.getMonth() + 1)
like image 167
Eugene Yokota Avatar answered Dec 04 '22 06:12

Eugene Yokota


The correct way to get a date value representing "yesterday" is this:

var today = new Date();
var yesterday = new Date(today.getTime() - (1000*60*60*24));

From there you can get the values of interest, like yesterday.getDate(),.

like image 22
Matt Ball Avatar answered Dec 04 '22 06:12

Matt Ball