I’m trying to get the past X days counting from today back using JavaScript.
However I’m only able to work out how to get today’s date but now the previous dates.
Say If I wanted the last 6 days including today, it to be printed as such:
- Monday Nov 5
- Sunday Nov 4
- Saturday Nov 3
- Friday Nov 2
- Thursday Nov 1
- Wednesday Oct 31
Heres what I’ve got so far to get the current day.
(function() {
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
Date.prototype.getMonthName = function() {
return months[this.getMonth()];
};
Date.prototype.getDayName = function() {
return days[this.getDay()];
};
})();
var todayDate = new Date(),
day = todayDate.getDate(),
weekday = todayDate.getDayName(),
month = todayDate.getMonthName(),
today = weekday + ' ' + month + ' ' + day;
using 86400000(miliseconds) approach will have a problem with daylight savings time
suppose
var d = new Date(“23/12/2012 00:00:00”);
var e = new Date(d.getTime() – 86400000);
and DST is +1 then e will be 23/12/2012 01:00:00
to solve this you can have a function to calculate the date before like:
then you can use it like
var todayDate = new Date(), c = 0;
for more details refer to this question