【HTML】获取当前时间并显示在网页上

首先在页面中我们直接写一个标签,然后给标签定义一个id,

这里我们用什么标签都可以,我们就用<span></span>演示吧,

代码如下:

<span id="clock" ></span>
    <script type="text/javascript">
    var clock = new Clock();
    clock.display(document.getElementById("clock"));
    </script>

上面我们实例化了一个Clock的对象,这里我们就在外部定义一个Clock的类,

获取当前时间并进行时间的格式化,代码如下:

复制代码
function Clock() {
    var date = new Date();
    this.year = date.getFullYear();
    this.month = date.getMonth() + 1;
    this.date = date.getDate();
    this.day = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")[date.getDay()];
    this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

    this.toString = function() {
        return "现在是:" + this.year + "年" + this.month + "月" + this.date + "日 " + this.hour + ":" + this.minute + ":" + this.second + " " + this.day; 
    };
    
    this.toSimpleDate = function() {
        return this.year + "-" + this.month + "-" + this.date;
    };
    
    this.toDetailDate = function() {
        return this.year + "-" + this.month + "-" + this.date + " " + this.hour + ":" + this.minute + ":" + this.second;
    };
    
    this.display = function(ele) {
        var clock = new Clock();
        ele.innerHTML = clock.toString();
        window.setTimeout(function() {clock.display(ele);}, 1000);
    };
}
复制代码

之后我们在页面头部中引入该js就好了

<script src="js/Clock.js" type=text/javascript></script>

效果:

 

posted @   木子欢儿  阅读(3117)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2019-12-01 【C语言】 删除一个字符串中重复的字符
2019-12-01 【C语言】将两个字符串连接起来
2019-12-01 【C语言】在有序数组中插入一个数,保证它依然有序
点击右上角即可分享
微信分享提示
主题色彩