js显示当前时间


undefined

闲着没事在闪存里看到有人需要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 @   浴火焚神  阅读(633)  评论(4编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示

"『一键投喂 软糖/蛋糕/布丁/牛奶/冰阔乐!』"

看板娘
欢迎阅读『js显示当前时间』