JavaScript以24小时制提供时间。不过,许多人不喜欢这种格式,希望转换为12小时制。下面的代码给出了一种解决办法。页面中有两个重要元素<h2>标签和单选按钮。脚本将时间写入前者,使用单选按钮进行选择。

HTML&CSS代码:

 
  
  1. <style type="text/css"> 
  2.     .centered { 
  3.         text-align:center; 
  4.         } 
  5.     label { 
  6.         padding-right:10px; 
  7.         } 
  8. </style> 
  9. <div class="centered"> 
  10.     <h2 id="showTime"></h2> 
  11.     Display 24-our Clock? 
  12.     <input  type="radio" name="timeClock" id="show24" checked="checked"/><label for="show24">Yes</label> 
  13.     <input  type="radio" name="timeClock" id="show12" checked="checked"/><label for="show12">No</label> 
  14. </div> 

JavaScript代码:

 
  
  1. <script type="text/javascript"> 
  2.     window.onload = showTheTime
  3.     function showTheTime(){ 
  4.         var now = new Date(); 
  5.          
  6.         document.getElementById("showTime").innerHTML = showTheHours(now.getHours())+ 
  7. showZeroFilled(now.getMinutes())+showZeroFilled(now.getSeconds())+showAmPm(); 
  8.         setTimeout(showTheTime,1000); 
  9.         //将几个函数的结果连接起来,构造出要在页面上显示的时间值,然后放入showTime的innerHTML属性。
  10.  
  11.         function showTheHours(theHour){ //此函数用来显示小时字段
  12.             if(show24Hour() || (theHour > 0 && theHour < 13)){
  13.                 return theHour; 
  14.             }
  15. //如果用户希望显示为24小时制,或者时间的小时部分大于0小于13,那么直接返回小时值theHour
  16.             if(theHour==0){ 
  17.                 return 12; 
  18.             } 
  19.             return theHour-12; 
  20. //大于等于13小于24的theHour减去12
  21.         } 
  22.          
  23.         function  showZeroFilled(inValue){ //此函数为10以下的加0
  24.             if(inValue>9){ 
  25.                 return ":" + inValue; 
  26.             } 
  27.             return ":0" + inValue; 
  28.         } 
  29.          
  30.         function showAmPm(){ //此函数在12小时制后面加上AM或PM。如果show24Hour返回为true,它返回空
  31.             if(show24Hour()){ 
  32.                 return ""; 
  33.             } 
  34.             if(now.getHours()<12){ 
  35.                 return " AM"; 
  36.             } 
  37.             return " PM";
  38.         } 
  39. function show24Hour(){//根据用户在页面上选择的单选按钮返回一个值,若选中show24,返回true。
  40. return document.getElementById("show24").checked;
  41. }
  42.     } 
  43. </script>