Working With Date Object JavaScript

Introduction

 
Most of the time, while working with different data type objects, there are not many issues but when it comes to Date and Time, there are always multiple test cases to pass.
 
In this blog, I would like to explain how to find a future or past date using JavaScript. 
 
We can get the current date and time using the new Date() constructor.
 
Many times, while programming, we get the requirement to send a reminder mail after 7, 14, or 30 days but most of the time, we do a manual calculation of adding +7 days or more. This will be a logical answer.
 
Here, consider the date is the 30th of any month and if 7 days are added, then the results will be illogical. Thus, the following code snippet will explain how to handle such a situation.   
  1. var d = new Date()    
  2. //d value Wed Jan 17 2018 16:22:46 GMT+0530 (India Standard Time)  
  3. new Date(Date.now())  
  4. Wed Jan 17 2018 16:28:31 GMT+0530 (India Standard Time) 
Note
 
Months are zero indexed.
  1. var reminderDate = new Date()  
  2. var currentDate = new Date(Date.now())  
  3. currentDate  
  4. // console output Wed Jan 17 2018 16:33:46 GMT+0530 (India Standard Time)  
  5. reminderDate.setDate(currentDate.getDate()+30) // adding 30 days  
  6. //1518778975066  
  7. reminderDate  
  8. //Fri Feb 16 2018 16:32:55 GMT+0530 (India Standard Time)  
In the above code snippet, when we added 30 days from the current date, the month part is automatically taken care of.