<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>实时日期与时间</title> </head> <body> <div id="dateDisplay">日期将显示在这里...</div> <div id="timeDisplay">时间将显示在这里...</div> <script type="text/javascript"> function clock_12h() { var today = new Date(); var year = today.getFullYear(); var month = (today.getMonth()+1).toString().padStart(2, '0'); var date = today.getDate().toString().padStart(2, '0'); var hour = today.getHours(); var minute = today.getMinutes().toString().padStart(2, '0'); var second = today.getSeconds().toString().padStart(2, '0'); var apm = "AM"; if (hour > 12) { hour = hour - 12; apm = "PM"; } else if (hour === 0) { hour = 12; // 对于0点需要特殊处理为12 AM } var weekday = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"][today.getDay()]; // 更新日期部分 document.getElementById("dateDisplay").innerHTML = "<span>" + year + "年" + month + "月" + date + "日 " + weekday + "</span>"; // 更新时间部分 var timeStr = hour + ":" + minute + ":" + second + " " + apm; document.getElementById("timeDisplay").innerHTML = "<span>" + timeStr + "</span>"; } var myTime = setInterval(clock_12h, 1000); </script> </body> </html>通过js分别独立获取年月日及时间,在这个例子中,我们有两个独立的<div>标签,一个用于显示日期(id为"dateDisplay"),另一个用于显示时间(id为"timeDisplay")。然后在clock_12h函数内部,我们分别更新这两个div的内容。