[Solved-7 Solutions] Add days to javascript date - javascript tutorial



Problem:

How to add days to current Date using JavaScript. Does JavaScript have a built in function like .Net's AddDay ?

Solution 1:

  • JavaScript provides the Date object for manipulating date and time. In between the various methods of the Date object, will be focusing in this post are the setDate(value) and getDate() which sets and gets the day of the month respectively.

Add Days to Date in JavaScript

<head>
    <title>Add Days to a Date from wikitechy.com</title>
    <script type="text/javascript">
        var newDt = new Date();
        document.writeln("Current Date :" + newDt + "<br/>");
        // add 6 days to the current date
        newDt.setDate(newDt.getDate() + 6);
        document.writeln("New Date :" + newDt);       
    </script>
</head>

Solution 2:

If we have the Moment Package it is very easy to get a new date simply adding days with the current date.

Syntax:

moment().add(Number, String);

Number represented the amount of days we want to add and string represent the keys of date like days, month, year, minute, second, etc.,

var m=moment().add(7, 'days')

Solution 3:

We can create one solution to add days:-

Date.prototype.add_Days = function(add_days) 
{
  var dat = new Date(this.valueOf());
  dat.setDate(dat.getDate() + add_days);
  return dat;
}

var dat = new Date();

alert(dat.add_Days(5))

We can use the setDate directly it created a problem in which a date is treated as a mutable class rather than an immutable structure. You can read about more such solutions and other resources by checking out foxinfotech.in.

Solution 4:

The best way to use setDate:

function addDays(date, days) 
{
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

Solution 5:

You want to find the date of tomorrow then use

var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);

But careful, this may be tricky. When setting "tomorrow", it only works with in the month because it's current value matches the year and month for "today". For example if today is 31st of december it might not work. Otherwise you setting to a date number like "32" normally will still work just fine to move it to the next month or next year comfortably.

Solution 6:

Better way of finding tomorrow is:

nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+1);

This solution does not have problem with daylight saving. Also, one can add/sub any offsets for years, months, days etc.

day=new Date(oldDate.getFullYear()-2,oldDate.getMonth()+22,oldDate.getDate()+61);

Solution 7:

We also find the nextday using the millisecond constructor

var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);

getTime()-gives us milliseconds since 1970
and 86400000 - the number of milliseconds in a day.


Related Searches to javascript tutorial - Add days to javascript date