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
DDDOriginal
2024-12-27 16:00:211041browse

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;
}

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));

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:
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