Skip to content
the poor coder

moment add days non destructive

Poor Man
Published
Reading time
1 min read
On this page

Moment Add Days Non Destructive#

Adding days to a date is a common requirement in web development. Moment.js is a popular JavaScript library that can be used to add days to dates in a non-destructive manner.

Method 1: Using Moment.js library#

Moment.js provides the add() method that can be used to add days to a date in a non-destructive manner. Here is an example:

Text

// Current date
var currentDate = moment();
// Add 7 days to current date
var newDate = currentDate.add(7, 'days');

The above code will add 7 days to the current date without modifying the original date value. The resulting newDate variable will hold the updated date value.

Method 2: Using vanilla JavaScript#

If you don't want to use a library like Moment.js, you can use vanilla JavaScript to add days to a date. Here is an example:

Text

// Current date
var currentDate = new Date();
// Add 7 days to current date
var newDate = new Date(currentDate.getTime() + (7 * 24 * 60 * 60 * 1000));

The above code uses the getTime() method to get the Unix timestamp of the current date, adds the number of milliseconds in 7 days, and creates a new Date object with the updated timestamp value. This approach is also non-destructive as it does not modify the original date value.

Conclusion#

Adding days to a date in a non-destructive manner is an important requirement in web development. Moment.js provides an easy way to achieve this, but vanilla JavaScript can also be used if you don't want to use a library. Both methods are non-destructive and can be used depending on your preference and project requirements.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC