Home >Web Front-end >JS Tutorial >Detailed explanation of JavaScript's operation of Date object (generating an array counting down 7 days)_javascript skills
Problem description:
Use JavaScript to generate a 7-day countdown array.
For example, today is October 1st, and the generated array is ["September 25th", "September 26th", "September 27th", "September 28th", "September 29th" ,"September 30th","October 1st"].
The difficulty is that you need to determine whether this month (and maybe the previous month) has 30 or 31 days, and there are also 28 or 29 days in February of Rui Nian.
Answer ideas:
It doesn’t need to be so complicated, it’s very simple in js, because the date object of js can participate in mathematical operations! ! ! Look at the code below:
var now = new Date('2012/3/2 12:00:00'); // 这个算法能自动处理闰年和非闰年。2012年是闰年,所以2月有29号 var s = ''; var i = 0; while (i < 7) { s += now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate() + '\n'; now = new Date(now - 24 * 60 * 60 * 1000); // 这个是关键!!!减去一天的毫秒数效果就是把日期往前推一天 i++; } console.log(s);
The result is as shown below:
If the requirement does not specify the time of a certain day, but is calculated based on the current time of the system, it is also possible.
Calculate this 7-day countdown array based on the current system time:
var now = new Date(); // This algorithm can automatically handle leap years and non-leap years. 2012 is a leap year, so February has the 29th
var s = '';
var i = 0;
while (i < 7) {
s = now.getFullYear() '/' (now.getMonth() 1) '/' now.getDate() 'n';
Now = new Date(now - 24 * 60 * 60 * 1000); // This is the key! ! ! The effect of subtracting the milliseconds of a day is to push the date forward by one day
i ;
}
console.log(s);
The result is as shown in the figure:
The above is the entire content of this article. I hope it will be helpful to everyone in learning js date object operations. The next article will introduce you to the date formatting issues in js. For more information, please click javascript Date format.