[javascript] Function to get yesterday's date in Javascript in format DD/MM/YYYY

I've been looking for a while to get yesterday's date in format DD/MM/YYYY. Here's my current code:

var $today = new Date();
var $dd = $today.getDate();
var $mm = $today.getMonth()+1; //January is 0!

var $yyyy = $today.getFullYear();
if($dd<10){$dd='0'+dd} if($mm<10){$mm='0'+$mm} $today = $dd+'/'+$mm+'/'+$yyyy;

With this, I get today's date in format DD/MM/YYYY (thanks SO). But when I try this:

var $yesterday = $today.getDate()-1;

as recommended on this site somewhere else (lost the link), I get an error saying that getDate() was not found for this object.

I'm using my script with Sahi, but I don't think it's linked, as Sahi has no trouble with Javascript.

Thank you in advance.

This question is related to javascript date

The answer is


Try this:

function getYesterdaysDate() {
    var date = new Date();
    date.setDate(date.getDate()-1);
    return date.getDate() + '/' + (date.getMonth()+1) + '/' + date.getFullYear();
}

You override $today in the if statement.

if($dd<10){$dd='0'+dd} if($mm<10){$mm='0'+$mm} $today = $dd+'/'+$mm+'/'+$yyyy;

It is then not a Date() object anymore - hence the error.