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
  • 38,868
  • 19
  • 114
  • 143
A_Elric
  • 3,508
  • 13
  • 52
  • 85

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
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 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
  • 232,168
  • 48
  • 399
  • 521
0

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

Abubakkar
  • 15,488
  • 8
  • 55
  • 83