Home>

### Explain in detail the operation of JavaScript on Date objects (generate an array with a countdown of 7 days)

Problem Description:

Use javascript to generate a 7-day countdown array.

For example today is October 1st, the generated array is ["September 25th", "September 26th", "September 27th", "September 28th", "September 29th", "9 "March 30", "October 1"].

The difficulty is to determine whether this month (and probably the previous month) is 30 or 31 days, and there are 28 or 29 days in February of Rui Nian.

Solution ideas:

Doesn't need to be that complicated,Very simple in js,Because the js date object 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 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 shown in the figure:

If demand is not specified for a certain day,But based on the current time of the system,It is also possible to calculate.

Based on the current system time,To calculate this 7-day countdown array:

var now=new date ();//This algorithm can automatically handle leap years and non-leap years.2012 is a leap year.So February 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 shown in the figure:

• Previous jQuery copy form element with source code sharing effect demo
• Next Reasons for automatic backslash before quotation marks after PHP form submission and three ways to close php magic quotes