Date.setHours () does not work

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

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

Where selectedTimeis the given time (the time I pass as a parameter).

So, suppose there selectedTimeis Tue Sep 16 19:15:16 UTC+0530 2014  I get:1410875116995

I want to get a response in datetime format. Am I something wrong here? Or is there another solution?

+4
source share
5 answers

The reason is that setHours(), setMinutes()etc. taken Integeras a parameter. From docs :

...

The setMinutes() The method sets the minutes for the specified date in local time.

...

Parameters:

An integer from 0 to 59 representing minutes.

So you can 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);
Hide result
+2

, -5.5 , (-5), , " ", 7 .

-, setHours ( ) Date (try console.log(cbTime)) ( ).

, Date , get*() .

+3

:

http://www.w3schools.com/jsref/jsref_sethours.asp

" 1 1970 " setHours.

, :

http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_sethours3

Edit: If you want to subtract 5.5 hours, you must first subtract 5 hours and then 30 minutes. If you wish, you can convert 5.5 hours to 330 minutes and subtract them as follows:

var d = new Date();
d.setMinutes(d.getMinutes() - 330);
document.getElementById("demo").innerHTML = d;
+2
source

Using:

  var cbTime = new Date();
        cbTime.setHours(cbTime.getHours() - 5.5)
        cbTime.toLocaleString();
+2
source

try the following:

 var cbTime = new Date();
    cbTime.setHours(cbTime.getHours() - 5.5)
    cbTime.toLocaleString();
-3
source

All Articles