我正在尝试制作一个在线世界时钟,但看不到时间......休息代码工作正常。
let a;
let dateTime;
let Time;
setInterval(() => {
var dateTime = new Date();
date = a.tolocaleDateString();
Time = a.gethours() + ':' + a.getminutes() + ':' + a.getseconds();
document.getElementById('time').innerHTML = Time + " on " + dateTime;
}, 1000);
你需要更清楚地命名你的变量。你引用
a
,但它没有定义。
此外,函数和变量在 JavaScript 中区分大小写。
setInterval(() => {
const now = new Date();
const date = now.toLocaleDateString();
const time = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
document.getElementById('time').innerHTML = time + ' on ' + date;
}, 1000);
<div id="time"></div>
您可以将
DateTimeFormat
存储为变量并调用其format
函数。这比每次调用带有选项的toLocaleDateString
更有效率。
此外,由于我们使用 i18n 格式化时间,因此数字会自动填充。
const
dateFormatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
}),
timeFormatter = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false,
});
const render = () => {
const now = new Date();
document.getElementById('time').innerHTML = `${
timeFormatter.format(now)
} on ${
dateFormatter.format(now)
}`;
};
render(); // Call it initially
setInterval(render, 1000);
<div id="time"></div>