实时时钟
显示当前时间,每秒更新
00:00:00
2024年1月1日 星期一
核心代码
let is24Hour = true;
let showSeconds = true;
function updateClock() {
const now = new Date();
let hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
// 12小时制转换
if (!is24Hour) {
const period = hours >= 12 ? ' PM' : ' AM';
hours = hours % 12 || 12;
return `${pad(hours)}:${pad(minutes)}${showSeconds ? ':' + pad(seconds) : ''}${period}`;
}
// 24小时制
return `${pad(hours)}:${pad(minutes)}${showSeconds ? ':' + pad(seconds) : ''}`;
}
function pad(num) {
return num.toString().padStart(2, '0');
}
function formatDate() {
const now = new Date();
const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
const weekday = weekdays[now.getDay()];
return `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日 ${weekday}`;
}