js显示当前时间


闲着没事在闪存里看到有人需要js显示当前时间,就一时兴起写了个。

输出格式:“2013年12月18日 星期三 上午9:05:00 ”。

复制代码
<script type="text/javascript">  function tick() {             var hours, minutes, seconds, xfile;             var intHours, intMinutes, intSeconds;             var today, theday;             today = new Date();             var d = [
"星期日",
"星期一",
"星期二",
"星期三",
"星期四",
"星期五",
"星期六"];

theday = today.getFullYear() + "年" + [today.getMonth() + 1] + "月" + today.getDate() + "日 " + d[today.getDay()];
            intHours = today.getHours();
            intMinutes = today.getMinutes();
            intSeconds = today.getSeconds();
            if (intHours == 0) {
                hours = "12:";
                xfile = " 午夜";
            } else if (intHours < 12) {
                hours = intHours + ":";
                xfile = " 上午";
            } else if (intHours == 12) {
                hours = "12:";
                xfile = " 正午";
            } else {
                intHours = intHours - 12
                hours = intHours + ":";
                xfile = " 下午";
            }
if (intMinutes < 10) { minutes = "0" + intMinutes + ":"; } else { minutes = intMinutes + ":"; } if (intSeconds < 10) { seconds = "0" + intSeconds + " "; } else { seconds = intSeconds + " "; } timeString = theday + xfile + hours + minutes + seconds; document.getElementById("lbClock").innerHTML = timeString; window.setTimeout("tick();", 100); } window.onload = tick; </script>
复制代码

PS:感谢undefined的指点,简化了很多。

以上是客户端时间,那么要想显示服务器时间怎么办呢?对于精确度要求不高的情况有个方案:

页面第一次打开时获取一次服务器时间,然后根据这个时间通过js计时器计算并显示时间。

复制代码
//计算时间 function getTime() {     serverTime.setSeconds(serverTime.getSeconds() + 1);     myTime.innerHTML = getTimeStr(serverTime); } //输出时间格式  2014-01-01 00:01:01 function getTimeStr(t) {     var result = t.getFullYear() + "-" + bl(t.getMonth() + 1) + "-" + bl(t.getDate()) + " " + bl(t.getHours()) + ":" + bl(t.getMinutes()) + ":" + bl(t.getSeconds());     return result; } //补零 function bl(n) {     return n.toString().length > 1 ? n : "0" + n; } //显示时间 function showTime() {     myTime = document.getElementById("lbClock");     //new Date无法转换 2014-01-01 01:01:01, - 替换成 / 之后转换正常     serverTime = new Date(myTime.innerHTML.replace(/-/g, "/"));     setInterval(getTime, 1000); } var myTime = '', serverTime = ''; window.onload = showTime;
复制代码
posted on 2015-12-15 10:05  土dou  阅读(344)  评论(0编辑  收藏  举报