Home > Web Front-end > JS Tutorial > body text

Increment given date in JavaScript

PHPz
Release: 2023-09-10 13:17:02
forward
1093 people have browsed it

在 JavaScript 中增加给定日期

In this article, we will discuss how to increment a given date using JavaScript. First, let’s analyze and understand the meaning of this sentence. Given a date x = "05-02-2023", we want to add y = 7 days to that date and print the resulting date "12-02-2023". As humans, we can manually add February 5th to 7 days and get the result. But we need JavaScript to do this programmatically.

We will discuss some techniques to do this in this article.

Use addDays() function

The addDays function accepts 2 parameters, namely the date and the number of days to be incremented. In the code below, we will add 7 days to the current date and print the added date to the console.

Example

function addDays(date, days) {
   
   // Function to add Days
   var result = new Date(date);
   result.setDate(result.getDate() + days);
   return result;
}
let date = new Date();
console.log("Current date is "+date);
let incrementedDate = addDays(date, 7);
console.log("Increment date is "+incrementedDate);
Copy after login

Output

Current date is Tue Mar 07 2023 11:38:38 GMT+0530 (India Standard Time)
Increment date is Tue Mar 14 2023 11:38:38 GMT+0530 (India Standard Time)
Copy after login

Use setDate() and getDate() functions

The getDate function returns an integer between 1 and 31, indicating the day of the month. Then use the setdate function to set the value of the variable to an incrementing date. Here we will add 14 days to the current date and display the result to the console. The increased number of days will be saved to the same variable "date", so there is no need for another variable.

Example

let date = new Date();
console.log("Current date is "+date);
date.setDate(date.getDate()+14);
console.log("Increment date is "+date);
Copy after login

Output

Current date is Tue Mar 07 2023 11:40:55 GMT+0530 (India Standard Time)
Increment date is Tue Mar 21 2023 11:40:55 GMT+0530 (India Standard Time)
Copy after login

User-defined functions

Here, instead of using any built-in function, we will create our own function to increment the date. We first extract the day integers of month, month and year from the given date and store them as variables d, m and y respectively. We then add the number of days to the d or day variable and convert it back to date format on return. Currently, this function has limited capabilities in adding days beyond 1 month, but this can at most be modified or avoided since a built-in function exists.

Example

function AddDays(start,days){
   var d=start.getDate();
   var m=start.getMonth()+1;
   
   //getMonth returns the index of the month hence +1 is added
   var y=start.getYear();
   
   //getYear returns the year minus 1900 in the current javascript version, hence 1900 is added to it below
   var newDate=m+"-"+(d+days)+"-"+(y+1900);
   return new Date(newDate);
}
today=new Date();
console.log("The date today is "+today);
console.log("The date after 5 days is "+AddDays(today,5));
Copy after login

Output

The date today is Tue Mar 07 2023 11:43:02 GMT+0530 (India Standard Time)
The date after 5 days is Sun Mar 12 2023 00:00:00 GMT+0530 (India Standard Time)
Copy after login

Add only working days

One may often see e-commerce websites using days increments to display estimated delivery times. This delivery time is usually not available on Sundays. Sundays must be excluded when calculating estimated delivery dates. Public holidays can also be excluded.

Here's how to Add 7 working days to the current date.

Example

function AddWorkingDays(start,days){
  
  // retrieve the index of the start date
   var d=start.getDay();
   var incrementby=days;
   if(d==0){
     
     // 0 stands for Sunday, if current day is a Sunday then add 1 day
      incrementby++;
   }
   if (d + incrementby >= 6) {
      
      //Subtract days in current working week from working days
      var remainingWorkingDays = incrementby - (5 - d);
      
      //Add current working week's weekend
      incrementby += 2;
      if (remainingWorkingDays > 5) {
         
         //Add two days for every working week by finding out how many weeks are included
         incrementby += 2 * Math.floor(remainingWorkingDays / 5);
        
         //Exclude the final weekend if the remainingWorkingDays is a equal to an exact number of weeks
         if (remainingWorkingDays % 5 == 0)
         incrementby -= 2;
      }
   }
   start.setDate(start.getDate() + incrementby);
   return start;
}
var today=new Date();
console.log("Current date is "+today);
console.log("8 working days later would be "+AddWorkingDays(today,8));
Copy after login

Output

Current date is Tue Mar 07 2023 11:45:58 GMT+0530 (India Standard Time)
8 working days later would be Fri Mar 17 2023 11:45:58 GMT+0530 (India Standard Time)
Copy after login

in conclusion

All the above methods allow you to add days, months and even years to a given date. The function of adding working days is very useful in the industry and can be used by e-commerce platforms, takeout websites, etc. In addition to these methods, we can also leverage the Moment.js library, but this will bring unnecessary complexity to the work. program.

The above is the detailed content of Increment given date in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!