In the forum today, we see the following question:
Problem Description:
Use JavaScript to generate an array of 7-day countdown.
For example today is October 1, the generated 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 also the year of February, 28 days or 29 days.
Solution Ideas:
Does not need to be so complex, in the js
very simple, because js
the date
object is can participate in the mathematical operation!!! Look at the following code:
var New // this algorithm can automatically handle leap years and non-leap years. 2012 is a leap year, so in February there is 29th var s = '; var i = 0; while (I < 7) { + = now.getfullyear () + '/' + (Now.getmonth () + 1) + '/' + now.getdate () + ' \ n '; New// This is the key!!! Subtracting the number of milliseconds in a day is the effect of pushing the date forward one day i++;} Console.log (s);
Results
If the requirement is not to specify the time of day, it is possible to calculate it based on the current time of the system.
Based on the current system time, the array of the 7-day countdown is calculated:
var New // this algorithm can automatically handle leap years and non-leap years. 2012 is a leap year, so in February there is 29th var s = '; var i = 0; while (I < 7) { + = now.getfullyear () + '/' + (Now.getmonth () + 1) + '/' + now.getdate () + ' \ n '; New// This is the key!!! Subtracting the number of milliseconds in a day is the effect of pushing the date forward one day i++;} Console.log (s);
Results:
Write here think of JS date format, learn more about Click here JavaScript dateformat.
JS problem with the operation of the Date object (generate an array of 7-day countdown)