Search notes:

JavaScript: Date arithmetic

Adding days

The following example tries to demonstrate how days might be added to a date.
It turns out that, at least on Firefox and Chrome, it is not possible to add fractional days. Instead, hours must be added with setHours(… getHours() + … )
<!DOCTYPE html>
<html>
<head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <title>Adding days</title>

  <script type="text/javascript">
    
    function main() {

      var out = document.getElementById('out');
      
      var dt = new Date (2014, 7, 11, 22, 23, 24); // Aug 11th 2014, 22 hours and 23 minutes

      dt.setDate(dt.getDate() + 17 );   // 17 days later (= Aug 28th 2014)
      out.innerHTML += dt.toString() + "<br>";

      dt.setDate(dt.getDate() + 365);   // Aug 28th 2015
      out.innerHTML += dt.toString() + "<br>";

      dt.setDate(dt.getDate() + 140);   // Jan 15 2016
      out.innerHTML += dt.toString() + "<br>";

   //
   // Trying to add fractional day…
   //
      dt.setDate(dt.getDate() + 5.0/24.0);
      out.innerHTML += dt.toString() + "<br>";

   //
   // Better approach?
   //
      dt.setHours(dt.getHours() + 5);
      out.innerHTML += dt.toString() + "<br>";

    }

  </script>

</head>
<body onload='main()';>

  <div id='out' style='font-family:monospace'></div>

</body>
</html>
Github repository about-javascript, path: /objects/Date/arithmetic/add-days.html
The output of this example, on my computer, is:
Thu Aug 28 2014 22:23:24 GMT+0200 (Central European Summer Time)
Fri Aug 28 2015 22:23:24 GMT+0200 (Central European Summer Time)
Fri Jan 15 2016 22:23:24 GMT+0100 (Central European Standard Time)
Sat Jan 16 2016 22:23:24 GMT+0100 (Central European Standard Time)
Sun Jan 17 2016 03:23:24 GMT+0100 (Central European Standard Time)

See also

The JavaScript Date object

Index