Twister1004 Posted November 2, 2008 Share Posted November 2, 2008 Hello everyone! I am fairly new to Javascript, and I obtained this script by w3schools and tweeked it a little to make it a 12 hour clock. Objective: 1) I can't figure out how to make it list AM or PM by the script. I've tried researching and I really didn't get anywhere. 2) I am trying to make it to where the time is set to the web server's time instead of the users local time. Meaning say if the user lived in EST and the webserver is based on PST, how would i be able to make it show in PST and not EST. <html> <head> <script type="text/javascript"> function startTime() { var today=new Date(); var h=today.getHours(); var m=today.getMinutes(); var s=today.getSeconds(); if (h>12){ h=h-12; } if (h == 0){ h=12; } // 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> </head> <body onload="startTime()"> <div id="txt"></div> </body> </html> any help, hints, codes, posting, or reading is appreciated! Thank you! Quote Link to comment Share on other sites More sharing options...
Psycho Posted November 2, 2008 Share Posted November 2, 2008 Hmm, you are defining checkTime() inside of startTime(). So it is getting redefined everytime startTime() is run. It should be moved outside of that function. There's also a more efficient way of doing that in my opinion. 1. To determine AM/PM you just need to determine if the original hours variable is less than 12. If so, the value is AM, else it is PM var am_pm = ( h < 12 ) ? 'am' : 'pm'; To determine the server time you will need to use server-side code to generate an offset to use on the page. I would use the 24 hour value for that purpose. Full code with some modifications: <html> <head> <script type="text/javascript"> var clientTime = new Date(); var clientHours = clientTime.getHours(); var serverHours = <?php echo date('H'); ?>; var serverOffset = clientHours - serverHours; function startTime() { var today = new Date(); var h = today.getHours() - serverOffset; var m = padZero(today.getMinutes()); var s = padZero(today.getSeconds()); var am_pm = ( h < 12 ) ? 'am' : 'pm'; if (h > 12) { h = h-12; } if (h == 0) { h = 12; } document.getElementById('txt').innerHTML=(h+':'+m+':'+s+' '+am_pm); t=setTimeout('startTime()', 500); } function padZero(numStr) { numStr = '0' + numStr; return numStr.substr(numStr.length-2); } </script> </head> <body onload="startTime()"> <div id="txt"></div> </body> </html> Quote Link to comment Share on other sites More sharing options...
Twister1004 Posted November 3, 2008 Author Share Posted November 3, 2008 Thank you mjdamato. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.