user1181942 user1181942 - 3 years ago 147
Javascript Question

date.setHours() not working

I am trying to subtract hours from a given date time string using javascript.
My code is like:

var cbTime = new Date();
cbTime = selectedTime.setHours(-5.5);


Where
selectedTime
is the given time (time that i pass as parameter).

So suppose
selectedTime
is
Tue Sep 16 19:15:16 UTC+0530 2014

Ans I get is :
1410875116995


I want answer in datetime format.
Am I doing something wrong here? Or there is some other solution?

Answer Source

The reason is that setHours(), setMinutes(), etc, take an Integer as a parameter. From the docs:

...

The setMinutes() method sets the minutes for a specified date according to local time.

...

Parameters:

An integer between 0 and 59, representing the minutes.

So, you could do this:

var selectedTime = new Date(),
    cbTime = new Date(); 
   
cbTime.setHours(selectedTime.getHours() - 5);
cbTime.setMinutes(selectedTime.getMinutes() - 30);

document.write('cbTime: ' + cbTime);
document.write('<br>');
document.write('selectedTime: ' + selectedTime);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download