1

I want to add 1.5 hours to a datetime :

var date = new Date('08/18/2016 19:00:00');

date.setHours(date.getHours() + 1.5);

Expected result :

date = 08/18/2016 20:30:00;

But I have :

date = 08/18/2016 20:00:00;

Why and how to do this?

  • 3
    Possible duplicate of [Adding hours to Javascript Date object?](http://stackoverflow.com/questions/1050720/adding-hours-to-javascript-date-object) – Mehdi Dehghani Aug 18 '16 at 18:12
  • @MehdiDehghani: Except that question and its answers are for whole hours, not fractional hours. – T.J. Crowder Aug 18 '16 at 18:13
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours : `An **integer** between 0 and 23, representing the hour.` So, with all due respect, RTFM. – PM 77-1 Aug 18 '16 at 18:15

1 Answers1

4

Why?

Because setHours doesn't accept fractional values. If you follow through the spec, you'll find it runs the hours value through the abstract ToInteger operation, which chops off the .5.

how to do this?

setHours actually accepts minutes (and seconds and such) as additional arguments:

date.setHours(date.getHours() + 1, date.getMinutes() + 30);

Alternately, you can do them separately:

date.setHours(date.getHours() + 1);
date.setMinutes(date.getMinutes() + 30);

Or as milliseconds:

date.setTime(date.getTime() + (1.5 * 60 * 60 * 1000));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875