1

I wrote some javascript in hopes of outputting time as hh:mm (EG: 15:45)

However my code is returning Nan:Nan

var timer = 24;
var time1 = new Date();
time1.setHours(time1.getHours + (6));
time1.setMinutes(time1.getMinutes());
document.write(time1.toString("hh:mm"));

Can someone help me understand why this isn't working as intended?

SomeKittens
  • 37,637
  • 19
  • 110
  • 141
A_Elric
  • 3,188
  • 12
  • 49
  • 80

3 Answers3

3

The getHours member is a function not a value. Hence you're multiplying a number by a method and getting NaN. Make sure to invoke the method

time1.setHours(time1.getHours() + (6));
JaredPar
  • 703,665
  • 143
  • 1,211
  • 1,438
  • As another question, this string still doesn't return quite right, it returns 18:47:26 GMT-0400 (Eastern Daylight Time) How do I get rid of everything after the 18:47? – A_Elric Oct 23 '12 at 16:47
  • @Damien.Bell take a look at this answer. It should cover what you're looking for http://stackoverflow.com/questions/1056728/formatting-a-date-in-javascript – JaredPar Oct 23 '12 at 16:50
1

The problem is that time1.getHours is a method. When you add 6 to a method, the result is NaN. You need to actually call it:

time1.setHours(time.getHours() + 6);
Ted Hopp
  • 227,407
  • 48
  • 383
  • 507
0

you can use document.write(time1.getHours()+":"+time1.getMinutes()); instead of it.

Abubakkar
  • 15,090
  • 6
  • 52
  • 80