Home > Web Front-end > JS Tutorial > JavaScript method to add days to a given time_javascript skills

JavaScript method to add days to a given time_javascript skills

WBOY
Release: 2016-05-16 15:18:06
Original
1507 people have browsed it

The example in this article describes the method of adding days to a given time in JavaScript. Share it with everyone for your reference, the details are as follows:

/**
* 时间相加处理函数
* @param date 需要计算的时间(xxxx-xx-xx)
* @param plusDays 要加的天数(整数)
*/
function calcuDate(date, plusDays) {
  var dateArray = date.split("-");
  var year = +dateArray[0];
  var month = +dateArray[1];
  var day = +dateArray[2];
  var oriDay = day;
  var secondMonthDays = ((year%4 === 0 && year%100 !== 0) || year%400 === 0) ? 29 : 28;
  while(plusDays>0) {
    oriDay = day
    day += plusDays;
    switch(month) {
      case 4:
      case 6:
      case 9:
      case 11:
        if(day > 30) {
          plusDays -= (30-oriDay)+1;
          month++;
          day = 1;
        } else {
          plusDays = 0;
        }
      break;
      case 2:
        if(day > secondMonthDays) {
          plusDays -= (secondMonthDays-oriDay)+1;
          month++;
          day = 1;
        } else {
          plusDays = 0;
        }
      break;
      default:
        if(day > 31) {
          plusDays -= (31-oriDay)+1;
          day = 1;
          month++;
        } else {
          plusDays = 0;
        }
    }
    if(month>12) {
      month = 1;
      year++;
    }
  }
  return createTimeString(year, month, day);
}

Copy after login

Of course, in addition to this method, there are other solutions, such as passing parameters with new Date. This can be considered one of them

Readers who are interested in more content related to JavaScript time and date operations can check out this site's special topic: "Summary of JavaScript time and date operation skills"

I hope this article will be helpful to everyone in JavaScript programming.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template