将“ am”或“ pm”添加到取决于时间的特定时间格式-Javascript

时间:2018-11-26 01:59:42

标签: javascript time

我有以下javaScript,以小时和分钟为单位显示时间。

有没有一种方法可以根据时间是在中午之前还是之后在时间旁边添加“ am”或“ pm”?

var t = new Date();
var time = document.getElementById("time");

time.textContent = t.getHours() + ":" + t.getMinutes();
<h3 class="time-holder">Current UK time: <span id="time">12:00</span></h3>

2 个答案:

答案 0 :(得分:1)

根据here改编的答案。

var d = new Date();
var hr = d.getHours();
var min = d.getMinutes();
if (min < 10) {
    min = "0" + min;
}
var ampm = "am";
if( hr > 12 ) {
    hr -= 12;
    ampm = "pm";
}


var time = document.getElementById("time");

time.textContent = hr + ":" + min + ampm;
<h3 class="time-holder">Current UK time: <span id="time">12:00</span></h3>

答案 1 :(得分:-1)

使用“ toLocaleTimeString()”方法代替“ getHours()”和“ getMinutes()”

例如:

var t = new Date();
var time = document.getElementById("time");

time.textContent = t.toLocaleTimeString('en-US');

来源: https://www.w3schools.com/jsref/jsref_tolocaletimestring.asp