JavaScript developers often use dates to store & display time-related information on their websites and applications. Sometimes you may need to add 1 day to current date in JavaScript. In this article, we will learn how to do this. It is very easy and many beginners are generally looking for tutorials about this.
How to Add 1 Day to Current Date
Let us say you have the following date object in JavaScript.
var date = new Date();
Each date object features a setDate() function that allows you to modify its value to a new one. While doing so, you are allowed to add or subtract days, instead of setting a new date value. Here is an example to add 1 day to current date. In this case, we first use date.getDate() function to get the preset date and then add 1 to it. We finally use it as an input to date.setDate() function.
date.setDate(date.getDate() + 1);
Please note, the above date change will happen in as per local time zone. If you are concerned about daylight saving in time, then it is better to first convert the date to Universal Time (UTC) and then add 1 day to it.
var date = new Date(); date.setUTCDate(date.getUTCDate() + 1);
In the above command, we use getUTCDate() instead of getDate() to get the present date’s UTC format. We also use setUTCDate() to set the new date value.
In fact, you can use the same approach to add more than 1 day but replacing 1 in the above commands with n number of days. On the other hand, if you want to subtract days from current date, instead of adding it, you can use ‘-‘ operator instead of ‘+’ above.
Here is an example to add 10 days to current date.
date.setDate(date.getDate() + 10);
On the other hand, here is an example to subtract 7 days from current date.
date.setDate(date.getDate() - 7);
There are plenty of third-party libraries that allow you to do this. For example, if you are using MomentJS library that provides many date-time related functions, you can add 1 day to current date as shown below.
var today = moment(); var tomorrow = moment(today).add(1, 'days');
In this article, we have learnt several ways to add dates to current day in JavaScript. You can use any of them as per your convenience. Incrementing and decrementing dates are a common requirement in many websites and applications, and you can use these commands to easily modify dates.
Also read:
How to Change One Character in Python String
How to Permanently Add Directory to Python Path
How to Install Python Package With .whl file
How to Convert JSON to Pandas DataFrame
How to Write List to File in Python
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.