Problem Description:
Use JavaScript to generate an array with a countdown of 7 days.
For example, today is October 1, the resulting array is ["September 25", "September 26", "September 27", "September 28", "September 29", "September 30", "October 1"].
The difficulty is to determine whether the month (and possibly the last month) is 30 days or 31 days, and that there are 28 or 29 days of the year in February.
Solution Idea:
Not so complex, in JS very simple, because JS Date object is can participate in mathematical operations!!! Look at the following code:
var now = new Date (' 2012/3/2 12:00:00 '); This algorithm can automatically handle leap years and non leap years. 2012 is a leap year, so February has 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!!!. Minus a day's millisecond effect is to push the date forward one day
i++;
Console.log (s);
The result is as shown in figure:
If the requirement is not to specify the time of day, it is also possible to calculate according to the current time of the system.
Calculates the last 7-day 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 there are 29th in February.
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!!!. Minus a day's millisecond effect is to push the date forward 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 that you learn JS Date object operations Help. The next article to introduce you to the date format of JS problem, for more information please click the JavaScript format.