Home > Web Front-end > JS Tutorial > How to Add Days to a Date in JavaScript?

How to Add Days to a Date in JavaScript?

DDD
Release: 2024-12-27 16:00:21
Original
1102 people have browsed it

How to Add Days to a Date in JavaScript?

Custom Date Function to Add Days in JavaScript

While JavaScript does not have a native .AddDay() function like .NET, we can easily create one using the Date prototype.

Implementation:

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}
Copy after login

Usage:

To add days to an existing Date object, simply invoke the .addDays() function with the desired number of days.

var date = new Date();

// Add 5 days to the current date
console.log(date.addDays(5));
Copy after login

This will create a new Date object with the specified number of days added to the original date.

The above is the detailed content of How to Add Days to a Date in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

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