JS problem with the operation of the Date object (generate an array of 7-day countdown)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.