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
You can see the demo below.