user1181942
user1181942

Reputation: 1607

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?

Upvotes: 6

Views: 19638

Answers (5)

Daniel Gasser
Daniel Gasser

Reputation: 5133

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

Upvotes: 4

user4045479
user4045479

Reputation:

Use:

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

Upvotes: 2

Wasif Shahjahan
Wasif Shahjahan

Reputation: 376

try this:

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

Upvotes: -3

lviggiani
lviggiani

Reputation: 6066

According to this:

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

You'll get "Milliseconds between the date object and midnight January 1 1970" as a return value of setHours.

Perhaps you're looking for this:

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

Edit: If you want to subtract 5.5 hours, first you have to subtract 5 hours, then 30 minutes. Optionally you can convert 5.5 hours to 330 minutes and subtract them like this:

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

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

Well first off setting the hours to -5.5 is nonsensical, the code will truncate to an integer (-5) and then take that as "five hours before midnight", which is 7PM yesterday.

Second, setHours (and other functions like it) modify the Date object (try console.log(cbTime)) and return the timestamp (number of milliseconds since the epoch).

You should not rely on the output format of the browser converting the Date object to a string for you, and should instead use get*() functions to format it yourself.

Upvotes: 3

Related Questions