Learning While Aging

Add days, months and years in JavaScript

This JavaScript function has been updated to better handle various scenarios, please check the new version here: https://learningpenguin.net/2017/07/20/add-days-months-years-date-javascript/

In ASP.NET, you can easily use DateTime.AddDays(), DateTime.AddMonths(), or DateTime.AddyYears() function to get a new DateTime object, but in JavaScript, there is no such built-in function. Since it is very common you have to do some date calculation or validation in JavaScript, I decided to write my own JavaScript function to add days, months, and years to a Date object to get a new Date object. Here is the JavaScript code and it is very self-explanatory:

   1: function AddDate(oldDate, offset, offsetType) {

   2:     var year = parseInt(oldDate.getFullYear());

   3:     var month = parseInt(oldDate.getMonth());

   4:     var date = parseInt(oldDate.getDate());

   5:     var hour = parseInt(oldDate.getHours());

   6:     var newDate;

   7:     switch (offsetType) {

   8:         case "Y":

   9:         case "y":

  10:             newDate = new Date(year + offset, month, date, hour);

  11:             break;

  12:

  13:         case "M":

  14:         case "m":

  15:             newDate = new Date(year, month + offset, date, hour);

  16:             break;

  17:

  18:         case "D":

  19:         case "d":

  20:             newDate = new Date(year, month, date + offset, hour);

  21:             break;

  22:

  23:         case "H":

  24:         case "h":

  25:             newDate = new Date(year, month, date, hour + offset);

  26:             break;

  27:     }

  28:     return newDate;

  29: }

The function AddDate() takes three parameters:

1. odlDate: A JavaScript Date object that will be worked on.

2. offset: An integer (positive or negative) that determines the number of date units that will be added to (or subtracted from) the oldDate object.

3. offsetType: The measurement unit of the offset parameter. “Y” or “y” means Year, “M” or “m” means Month, “D” or “d” means Day, “H” or “h” means Hour. Likewise, you can modify the above function to allow Minute, Second, and Millisecond.

Example:

1. To get the date that is 21 days from the current date:

   1: var date21 = AddDate(new Date(), "21", "D");

2. To get the date that is 2 years before the current date:

   1: var date2 = AddDate(new Date(), "2", "Y");

Hope this helps.

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Khurram Ishaque
Khurram Ishaque
6 years ago

Is this script suppose to cover the end of year till next year date.
For example, if I want to give 25 dec, and add 10 days, it should switch to new year automatically, without being forcing myself to put checks for it.