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?
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)
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()
,.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With