简体   繁体   English

以 12 小时制显示当前时间? - Javascript

[英]Display current time in 12 hour time? - Javascript

I'm trying to add the current time to a website using JS and I found a working solution but the problem is that it works for 24-hour format time and I'm struggling to figure out how I might modify it to display 12-hour format time... See Fiddle HERE: https://jsfiddle.net/7hjsaqdu/1/我正在尝试使用 JS 将当前时间添加到网站,我找到了一个可行的解决方案,但问题是它适用于 24 小时格式时间,我正在努力弄清楚如何修改它以显示 12-小时格式时间......在这里见小提琴: https://jsfiddle.net/7hjsaqdu/1/

function display_c() {
  var refresh = 1000; // Refresh rate in milli seconds
  mytime = setTimeout('display_ct()', refresh)
}

function display_ct() {
  var x = new Date()
  var x1 = x.getMonth() + 1 + "/" + x.getDate() + "/" + x.getYear();
  x1 = x1 + " - " + x.getHours() + ":" + x.getMinutes() + ":" + x.getSeconds();
  var hour = x.getHours();
  var minute = x.getMinutes();
  var second = x.getSeconds();
  if (minute < 10) {
    minute = '0' + minute;
  }
  if (second < 10) {
    second = '0' + second;
  }
  var x3 = hour + ':' + minute + ':' + second
  document.getElementById('ct').innerHTML = x3;
  display_c();
}

HTML: HTML:

<body onload=display_ct();>
<span id='ct' ></span>

You can use Date.prototype.toLocaleTimeString()您可以使用 Date.prototype.toLocaleTimeString()
Mozilla Developer Docs Mozilla 开发者文档

let formattedTime = date.toLocaleTimeString('en-US', {
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric',
    hour12: true
});

document.getElementById('ct').innerHTML = formattedTime;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM