PDA

View Full Version : Javascript Clock h:mm TT format

jason_kelly
05-24-2012, 09:53 PM
Hello,

How could the simple code below for a javascript be modified such that the clock will display in the format h:mm TT (ie. 4:52 PM) as opposed to its current setting right now of: hh:mm:ss?

<html>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}

function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>

Any help with this is greatly and much appreciated.

Cheers,

Jay

007julien
05-24-2012, 10:52 PM
Converting from 24 hour clock to AM / PM
0000 to 0059 add 12 hours to 0 => 12 hours
0000 --> 12 midnight
0015 --> 12:15 AM
0030 --> 12:30 AM
0059 --> 12:59 AM

0100 to 1159 straight conversion to AM
0100 --> 01:00 AM
0300 --> 03:00 AM
0700 --> 07:00 AM
0830 --> 08:30 AM
1000 --> 10:00 AM
1159 --> 11:59 AM
1200 to 1259 straight conversion to PM
1200 --> 12 noon
1215 --> 12:15 PM
1230 --> 12:30 PM
1259 --> 12:59 PM
1300 to 2359 subtract 12 hours
1300 --> 01:00 PM
1500 --> 03:00 PM
1800 --> 06:00 PM
2030 --> 08:30 PM
2215 --> 10:15 PM
2359 --> 11:59 PM

Then script could be

function startTime(){
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
// we compare numbers (and not strings)
var s='AM';if (11<h) s='PM';
if (h<1) h='12';
if (12<h) h-=12;
// add a zero in front of numbers<10
h=checkTime(h);
m=checkTime(m);
var r=h+":"+m+" "+s;
r=r.replace(/12:00 AM/,'12 midnight').replace(/12:00 PM/,'12 noon');

document.getElementById('txt').innerHTML=r;
t=setTimeout(startTime,500);// to indicate the function (a javascript object and not a string)
}
startTime();// to execute the function
function checkTime(i){if (i<10) i="0"+i;return i;}