2014-10-19 107 views
0

我有一个Rails应用程序,我在我的应用程序布局中显示实时时钟。我使用此代码,使其工作:Javascript更改军事和上午/下午onclick之间的时间

<div id="time" class="time_display"></div> 
<script type="text/javascript"> 
function checkTime(i) { 
    if (i < 10) { 
     i = "0" + i; 
    } 
    return i; 
} 

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('time').innerHTML = h + ":" + m + ":" + s; 
    t = setTimeout(function() { 
     startTime() 
    }, 500); 
} 
startTime(); 
</script> 

我想什么能够做的就是以某种方式给用户在军用时间和定期AM/PM时间实时时钟之间切换的选项包括上午/下午,但点击分区。

我已经做了一些搜索,但没有发现任何工作得很好。我愿意接受任何可能是JS或jQuery的解决方案。

任何帮助将不胜感激。如果我的问题不清楚,请告诉我。

回答

0

真:

var ampm = 'am'; 
if(hours > 11){ 
    ampm = 'pm'; 
    if(hours > 12)hours = hours-12; 
} 
if(hours === 0)hours = 12; 

此外,你可以这样做:

today.toLocaleString().split(',')[1]; 
0

这里是代码。它得到的只是旁边剔更新,但你能设法解决这个问题,如果你想

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

 
function startTime() { 
 
    var today = new Date(); 
 
    var h = today.getHours(); 
 
    var m = today.getMinutes(); 
 
    var s = today.getSeconds(); 
 
    var ampm = h >= 12 ? 'pm' : 'am'; 
 
    // add a zero in front of numbers<10 
 
    m = checkTime(m); 
 
    s = checkTime(s); 
 
    var timer = document.getElementById('time'); 
 
    if (timer.type == 'r') { 
 
     h = h % 12; 
 
     h = h ? h : 12; 
 
     timer.innerHTML = h + ":" + m + ":" + s + " " + ampm; 
 
    } else 
 
     timer.innerHTML = h + ":" + m + ":" + s; 
 
    t = setTimeout(function() { 
 
     startTime() 
 
    }, 500); 
 
    document.getElementById('time').onclick = function() { 
 
     if (this.type == 'r') 
 
      this.type = 'm'; 
 
     else 
 
      this.type = 'r'; 
 
    } 
 
} 
 
startTime();
<div id="time" class="time_display"></div>

相关问题