JavaScript: get yesterday's date

JavaScript: get yesterday's date

How to get yesterday's date in JavaScript.

I generally surf snippet repositories when I'm looking for some code that might be useful for my work projects. On Snipplr I found a simple PHP snippet that displays yesterday's date. Is it possible to achieve the same result in JavaScript? Let's see.

We need to use milliseconds in order to calculate the difference between today's and yesterday's date. Fortunately, the solution is pretty simple:

var todayTimeStamp = +new Date; // Unix timestamp in milliseconds
var oneDayTimeStamp = 1000 * 60 * 60 * 24; // Milliseconds in a day
var diff = todayTimeStamp - oneDayTimeStamp;
var yesterdayDate = new Date(diff);
var yesterdayString = yesterdayDate.getFullYear() + '-' + (yesterdayDate.getMonth() + 1) + '-' + yesterdayDate.getDate();

alert(yesterdayString);​

This method applies also to other time spans, for example a week ago or a month ago. By using milliseconds and the Unix format on the Date object, we can actually perform many calculations with dates in JavaScript.

You can see the demo below.

Demo

Live demo