JavaScript在网页上显示当前时间,可以选择12小时格式还是24小时格式
<html> <head> <title>Javascript clock</title> <head> <style type="text/css"> form,label { font-family:arial, sans-serif, helvetica, "times new roman"; font-size:10pt; /* increase or decrease the value to change the size of the font */ } h1 { font-family:arial, sans-serif, helvetica, "times new roman"; } </style> <script type="text/javascript"> <!-- hide the code from old browsers that do not support javascript /* Original: daniusr You are welcomed to modify this script to your needs. This script retrieves the time from the internal system clock, so it is up to you to make sure the time is accurate or correct. */ function clock() { var today = new Date(); var hours = today.getHours(); var minutes = today.getMinutes(); var seconds = today.getSeconds(); var time_holder; // holds the time //if the first radio button is checked display 12-hours format time if(timeForm.stime[0].checked) { // add "AM" or "PM" if the 12-hours format is chosen var ampm = ((hours >= 12) ? " PM" : " AM"); // convert the hour to 12-hours format // javascript returns midnight as 0, but since the time is in the 12-hours format // force javascript to return 12 hours = ((hours == 0) ? "12" : (hours > 12) ? hours - 12 : hours); // add a leading zero if less than 10 minutes = ((minutes < 10) ? "0" + minutes : minutes); seconds = ((seconds < 10) ? "0" + seconds : seconds); time_holder = hours + ":" + minutes + ":" + seconds + ampm; document.getElementById('jsClock').innerHTML = time_holder; } if(timeForm.stime[1].checked) { // add a leading zero if less than 10 hours = ((hours < 10) ? "0" + hours : hours); minutes = ((minutes < 10) ? "0" + minutes : minutes); seconds = ((seconds < 10) ? "0" + seconds : seconds); time_holder = hours + ":" + minutes + ":" + seconds; document.getElementById('jsClock').innerHTML = time_holder; } if((!timeForm.stime[0].checked) && (!timeForm.stime[1].checked)) { document.getElementById('jsClock').innerHTML = "Please select a time format."; } // keep the clock ticking setTimeout("clock()", 1000); } // end hiding --> </script> </head> <body onload="javascript:clock()"> <h1 id="jsClock" style="margin:0" align="center"></h1> <form name="timeForm" style="margin:0"> time format: <label for="ci"><input type="radio" name="stime" id="ci">12-hours format</label> <label for="mi"><input type="radio" name="stime" id="mi">24-hours format</label> </form> </body> </html>