Click to See Complete Forum and Search --> : Digital clock, help!


gokou
01-06-2003, 06:00 PM
I am having a little trouble with this digital clock. It runs, but not the way I want it to and I can't find the problem. The problem I am having is when it's 12:00 pm(I dunno about am) it shows the hour as 0. I've set a variable to turn that 0 into 12, but maybe it's wrong?

Here's the script.

<html>
<head>
<script language="javascript">
function runningtime()
{

var now=new Date()

var ampm=now.getHours()
if (ampm > 12)
{nampm = "pm"}
else
{nampm = "am"}

var hr=now.getHours()
if (hr >=12)
{nhr = hr - 12}
else
{nhr=hr}

if (hr == 0)
{nhr = "12"}
else
{nhr = nhr}

var min=now.getMinutes()
if (min < 10)
{nmin="0" +min}
else
{nmin=min}

var sec=now.getSeconds()
if (sec < 10)
{nsec="0" + sec}
else
{nsec=sec}

if (nsec >= 60)
{nnsec="00"}
else
{nnsec=nsec}

var printit="The time is: " +nhr+ ":" +nmin+ ":" +nnsec+ ":" +nampm

document.clockform.clocktext.value=printit

setTimeout("runningtime()","1000")
}

</script>
</head>
<body bgcolor="black" onLoad="runningtime()">
<center><form name="clockform">
<input type="text" name="clocktext">
</form>
</body>
</html>

ChikoritaPro
01-06-2003, 06:14 PM
var now=new Date()

var ampm=now.getHours()
if (ampm > 12)
{nampm = "pm"}
else
{nampm = "am"}

var hr=now.getHours()
if (hr >=12) // Problem located here.
{nhr = hr - 12}
else
{nhr=hr}

Note the:
if(hr>=12)
{nhr=hr-12}

12 is greater than or equal to 12. 12 subtracted by 12 is 0. Get rid of the equal sign of hr>=12 :).

ChikoritaPro
01-06-2003, 06:17 PM
I notice another problem.

if (hr == 0)
{nhr = "12"}
else
{nhr = nhr} // Problem located here.

I don't think you want the variable 'nhr' to equal to 'nhr' (itself). Change it to nhr=hr :).

gokou
01-06-2003, 07:03 PM
Thanks i'll see if it works at 12:00.

As for these lines of code:

if (hr == 0)
{nhr = "12"}
else
{nhr = nhr}

You don't wanna change that part. If you do the hour goes by military time or whatever that other time is. What your doing is changing the original value of nhr(nhr = hr - 12) by changing it to nhr = "12" then the else just returns nhr to it's original value by doing nhr = nhr(back to nhr = hr - 12). Try it, you'll see what I mean. Just cut/paste it into notepad and save it as a html file(you already knew that though).