【问题标题】:How to get current time in a format hh:mm AM/PM in Javascript?如何在 Javascript 中以 hh:mm AM/PM 格式获取当前时间?
【发布时间】:2015-07-04 06:15:04
【问题描述】:

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

我试图做类似的事情: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 小时添加到最终结果中。你能帮助我吗? 谢谢!

【问题讨论】:

标签: javascript date datetime datetime-format


【解决方案1】:

使用Date 方法设置和检索时间并构造时间字符串,类似于sn-p。

[edit] 只是为了好玩:添加了一个更通用的方法,使用 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');

  
 
}
&lt;div id="result"&gt;&lt;/div&gt;

【讨论】:

  • 不错!不知道为什么这里关于时间的大多数问题都要求不可读的 UNIX 时间戳......就像他们的项目/应用程序中谁需要它一样大声笑
【解决方案2】:

请注意,接受的答案虽然不错,但似乎不符合以下格式要求: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>

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      很简单,你可以这样做

      
      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。

      【讨论】:

        猜你喜欢
        • 2018-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-17
        • 1970-01-01
        • 1970-01-01
        • 2013-09-15
        • 2010-09-26
        相关资源
        最近更新 更多