如何以 hh:mm AM/PM in Javascript 格式获取当前时间?

How to get current time in a format hh:mm AM/PM in Javascript?

我有一个 Javascript,我需要以 HH:MM AM/PM 的格式粘贴当前时间。有一个问题 - 我需要输入从现在开始两个小时后开始的时间,例如,我需要输入 9:23PM 而不是 7:23PM,等等

我尝试过类似的操作:var dateFormat = new Date("hh:mm a") 但没有成功。我也尝试使用:

var today = new Date();
var time = today.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "")
alert(time);

但我只看到了例如18:23 而不是 6:23 PM(可能是因为 toLocaleTimeString() 和我在欧洲的位置)——也许有一些统一的方法可以在全世界工作?另外,我不知道如何将 2 小时添加到最终结果中。你能帮助我吗? 谢谢!

使用 Date 方法来设置和检索时间并构造一个时间字符串,类似于代码段中的内容。

[编辑] 只是为了好玩:添加了一个更通用的方法,使用 2 Date.prototype 扩展。

var now = new Date();
now.setHours(now.getHours()+2);
var isPM = now.getHours() >= 12;
var isMidday = now.getHours() == 12;
var result = document.querySelector('#result');
var time = [now.getHours() - (isPM && !isMidday ? 12 : 0), 
            now.getMinutes(), 
            now.getSeconds() || '00'].join(':') +
           (isPM ? ' pm' : 'am');
            
result.innerHTML = 'the current time plus two hours = '+ time;

// a more generic approach: extend Date
Date.prototype.addTime = addTime;
Date.prototype.showTime = showTime;

result.innerHTML += '<h4>using Date.prototype extensions</h4>';
result.innerHTML += 'the current time plus twenty minutes = '+ 
                      new Date().addTime({minutes: 20}).showTime();
result.innerHTML += '<br>the current time plus one hour and twenty minutes = '+ 
                      new Date().addTime({hours: 1, minutes: 20}).showTime();
result.innerHTML += '<br>the current time <i>minus</i> two hours (format military) = '+ 
                      new Date().addTime({hours: -2}).showTime(true);
result.innerHTML += '<br>the current time plus ten minutes (format military) = '+ 
                      new Date().addTime({minutes: 10}).showTime(true);


function addTime(values) {
  for (var l in values) {
    var unit = l.substr(0,1).toUpperCase() + l.substr(1);
    this['set' + unit](this['get' + unit]() + values[l]);
  }
  return this;
}

function showTime(military) {
  var zeroPad = function () {
    return this < 10 ? '0' + this : this;
  };
  
  if (military) {
    return [ zeroPad.call(this.getHours()),
             zeroPad.call(this.getMinutes()),
             zeroPad.call(this.getSeconds()) ].join(':');
  }
  var isPM = this.getHours() >= 12;
  var isMidday = this.getHours() == 12;
  return time = [ zeroPad.call(this.getHours() - (isPM && !isMidday ? 12 : 0)),
                  zeroPad.call(this.getMinutes()),
                  zeroPad.call(this.getSeconds()) ].join(':') +
                (isPM ? ' pm' : ' am');

  
 
}
<div id="result"></div>

请注意,已接受的答案虽然不错,但似乎不符合格式要求:HH:MM AM/PM。它 returns 午夜为“0:0:38am” 等等。

有很多方法可以做到这一点,下面显示了一种替代方法。点击"Run Code Snippet"进行测试。

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Clock</title>
</head>
<body>
<span id="clock"  style="font-family: monospace; font-size: 48px; background-color: black; color: lime; padding: 10px;">00:00:00 AM</span>
<script type="text/javascript">

function getTime( ) {
 var d = new Date( ); 
 d.setHours( d.getHours() + 2 ); // offset from local time
 var h = (d.getHours() % 12) || 12; // show midnight & noon as 12
 return (
  ( h < 10 ? '0' : '') + h +
  ( d.getMinutes() < 10 ? ':0' : ':') + d.getMinutes() +
                // optional seconds display
  // ( d.getSeconds() < 10 ? ':0' : ':') + d.getSeconds() + 
  ( d.getHours() < 12 ? ' AM' : ' PM' )
 );
 
}

var clock = document.getElementById('clock');
setInterval( function() { clock.innerHTML = getTime(); }, 1000 );
</script>
</body>
</html>

您可以用一行代码将当前时间转换为 12 小时格式

new Date().toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric' });

并在您当前的时间基础上增加两个小时

Date.now() + 2 * 60 * 60 * 1000

所以你可以用一行简单的代码来完成:

new Date(Date.now() + 2 * 60 * 60 * 1000).toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric' });

简单地说,你可以这样做


const date = new Date()
const options = {
  hour: 'numeric',
  minute: 'numeric',
  hour12: true
};
const time = new Intl.DateTimeFormat('en-US', options).format(date)
console.log(time)

更多详细信息,您可以参考MDN docs