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?
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?
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));