Javascript时间显示上午/下午从电脑(快速调整)

时间:2013-08-24 07:02:06

标签: javascript time clock code-snippets

如果可以的话,只需要快速调整即可。我从网上获得了这个代码,并且只想在时钟/时间结束时添加一个上午/下午。非常感谢......

<script>
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(function(){startTime()},500);
}

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

<div id="txt"></div>

2 个答案:

答案 0 :(得分:1)

或者,如果您还希望以12小时格式显示:

<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);
var hd=h;
document.getElementById('txt').innerHTML=(hd=0?"12":hd>12?hd-12:hd)+":"+m+":"+s+" "+(h<12?"AM":"PM");
t=setTimeout(function(){startTime()},500);
}

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

答案 1 :(得分:0)

这应该可以解决问题。

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);

    var suffix;        
    if (h >= 12 && h < 24){
        suffix = "pm";
    } else {
        suffix = "am";
    }    
    document.getElementById('txt').innerHTML = h + ":" + m + ":" + s + " " + suffix;

    t = setTimeout(function () {
        startTime()
    }, 500);
}

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