使用Date对象可轻松获取当前时间。首先创建new Date()实例,再通过getFullYear()、getMonth()+1、getDate()等方法提取年月日时分秒,注意月份从0开始需加1。结合setInterval每秒调用updateClock函数,利用toLocaleDateString和toLocaleTimeString格式化并更新页面显示,实现动态时钟。完整HTML示例包含页面加载后立即执行且每秒刷新的实时时间展示。

JavaScript 获取当前时间非常简单,主要依靠内置的 Date 对象。下面是一套完整、实用的代码示例,帮助你在网页中获取并显示当前时间。
使用 new Date() 可以创建一个表示当前日期和时间的对象:
const now = new Date(); console.log(now); // 输出当前完整时间
从 Date 对象中提取具体的时间单位,可以使用以下方法:
function getCurrentTime() {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1;
const day = now.getDate();
const hour = now.getHours();
const minute = now.getMinutes();
const second = now.getSeconds();
return `${year}年${month}月${day}日 ${hour}:${minute}:${second}`;
}
为了让页面上的时间动起来,可以用 setInterval 每隔1秒刷新一次显示:
function updateClock() {
const now = new Date();
const timeString = now.toLocaleTimeString(); // 简化格式:14:30:25
document.getElementById("clock").textContent = timeString;
}
// 页面加载完成后开始更新
setInterval(updateClock, 1000);
updateClock(); // 立即执行一次,避免初始空白
将以下代码保存为 .html 文件,直接在浏览器中打开即可看到实时时间:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>JS显示当前时间</title>
</head>
<body>
<h2>当前时间:<span id="clock"></span></h2>
<script>
function updateClock() {
const now = new Date();
const timeString = now.toLocaleTimeString("zh-CN");
const dateString = now.toLocaleDateString("zh-CN");
document.getElementById("clock").textContent =
dateString + " " + timeString;
}
setInterval(updateClock, 1000);
updateClock();
</script>
</body>
</html>
基本上就这些。你可以根据需要调整格式,比如只显示时间、加星期、用24小时制等。核心是掌握 Date 对象的使用方式。不复杂但容易忽略细节,比如月份从0开始的问题。
以上就是js脚本如何获取当前时间_js获取当前时间并显示的完整代码教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号