如何在 Javascript 中以 hh:mm AM/PM 格式获取当前时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29867862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get current time in a format hh:mm AM/PM in Javascript?
提问by randomuser1
I have a Javascript in which I need to paste the current time in a format HH:MM AM/PM. There's one catch - I need to put the time that starts in two hours from now, so for example, instead of 7:23PM I need to put 9:23PM, etc.
我有一个 Javascript,我需要在其中以 HH:MM AM/PM 格式粘贴当前时间。有一个问题 - 我需要把从现在起两小时后开始的时间,例如,而不是 7:23PM 我需要把 9:23PM 等等。
I tried to do something like: var dateFormat = new Date("hh:mm a")but it didn't work. I also tried to use:
我试图做类似的事情:var dateFormat = new Date("hh:mm a")但它没有用。我也尝试使用:
var today = new Date();
var time = today.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "")
alert(time);
but all I've seen was e.g. 18:23 instead of 6:23 PM (probably because of toLocaleTimeString() and my location in Europe) - maybe there's some unified way to do that that will work all around the World?. Also, I don't know exactly how to add the 2 hours to the final result. Can you help me? Thanks!
但我所看到的只是 18:23 而不是下午 6:23(可能是因为 toLocaleTimeString() 和我在欧洲的位置) - 也许有一些统一的方法可以做到这一点,这将适用于世界各地?。另外,我不知道如何将 2 小时添加到最终结果中。你能帮助我吗?谢谢!
采纳答案by KooiInc
Use Datemethods to set and retrieve time and construct a time string, something along the lines of the snippet.
使用Date方法来设置和检索时间并构造一个时间字符串,类似于代码片段的内容。
[edit] Just for fun: added a more generic approach, using 2 Date.prototypeextensions.
[编辑] 只是为了好玩:添加了一个更通用的方法,使用 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>
回答by acesmndr
You can convert the current time to 12 hour format with a one liner
您可以使用一个班轮将当前时间转换为 12 小时格式
new Date().toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric' });
And to add two hours to your current time
并为您的当前时间增加两个小时
Date.now() + 2 * 60 * 60 * 1000
Date.now() + 2 * 60 * 60 * 1000
So you can do it in a simple one line as:
所以你可以用简单的一行来完成:
new Date(Date.now() + 2 * 60 * 60 * 1000).toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric' });
new Date(Date.now() + 2 * 60 * 60 * 1000).toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric' });
回答by Naren
Simply, you can do this
很简单,你可以这样做
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)
For more details, you can read [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat]
有关更多详细信息,您可以阅读 [ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat]
回答by Roberto
Note that the accepted answer, while good, does not appear to meet the format requirement of: HH:MM AM/PM. It returns midnight as "0:0:38am" and so forth.
请注意,接受的答案虽然很好,但似乎不符合以下格式要求:HH:MM AM/PM。它返回午夜为“0:0:38am”等等。
There are many ways one could do this and one alternative is shown below. Click the "Run Code Snippet" to test.
有很多方法可以做到这一点,下面显示了一种替代方法。单击“运行代码片段”进行测试。
<!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>

