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

9

我有一个Javascript程序,在其中我需要以HH:MM AM/PM的格式粘贴当前时间。有一个限制-我需要放置从现在开始两个小时后开始的时间,因此例如,我需要放9:23 PM而不是7:23 PM等。

我尝试了以下代码:var dateFormat = new Date("hh:mm a")但是它没有起作用。我还尝试使用:

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

但是我看到的都是18:23,而不是6:23 PM(可能是因为使用了toLocaleTimeString()函数,并且我的位置在欧洲) - 或许有一种统一的方式可以使其在全球范围内工作?此外,我不知道如何将2小时添加到最终结果中。能帮帮我吗? 谢谢!


1
只需将2小时添加到日期对象中并进行格式化即可。 - Jonathan
也许这些旧帖子可以帮到您:"如何在JavaScript中以12小时AM/PM格式显示日期时间?" --> https://dev59.com/-Gox5IYBdhLWcg3w6oj0 或者 "如何在JavaScript中以12小时AM/PM格式显示日期时间?" --> http://stackoverflow.com/questions/24315100/convert-utc-time-to-hours-minutes-and-am-pm-format-in-javascript - nicolaus-hee
我还建议使用moment.js,这是一个相当小的库,用于操作和格式化日期对象。http://momentjs.com/ - Andrew Lavers
这回答解决了你的问题吗?如何在JavaScript中以12小时AM/PM格式显示日期时间? - Tariqul Islam
4个回答

16

您可以使用一行代码将当前时间转换为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' });


6
使用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>


1
不错!不知道为什么这里大多数关于时间的问题都要求使用无法阅读的UNIX时间戳...谁需要在他们的项目/应用程序中使用它呢,哈哈 - Leon Gaban

3

简单来说,你可以这样做


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 文档的内容。


1
请注意,虽然被接受的答案很好,但似乎没有满足格式要求:HH:MM AM/PM。它将午夜返回为“0:0:38am”等等。
有许多方法可以做到这一点,下面展示了其中一种替代方案。单击“运行代码片段”进行测试。

<!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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接