如何以 12 小时 AM/PM 格式显示 JavaScript 日期时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8888491/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:56:26  来源:igfitidea点击:

How do you display JavaScript datetime in 12 hour AM/PM format?

javascriptdatetimedatetimeformat

提问by bbrame

How do you display a JavaScript datetime object in the 12 hour format (AM/PM)?

如何以 12 小时格式 (AM/PM) 显示 JavaScript 日期时间对象?

回答by bbrame

function formatAMPM(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return strTime;
}

console.log(formatAMPM(new Date));

回答by Abhay Kumar

If you just want to show the hours then..

如果您只想显示小时,那么..

var time = new Date();
console.log(
  time.toLocaleString('en-US', { hour: 'numeric', hour12: true })
);  

Output : 7 AM

输出:早上 7 点

If you wish to show the minutes as well then...

如果您还想显示会议记录,那么...

var time = new Date();
console.log(
  time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })
);

Output : 7:23 AM

输出:上午 7:23

回答by Mike Christensen

You can also consider using something like date.js:

你也可以考虑使用类似date.js 的东西:

<html>
<script type="text/javascript" src="http://www.datejs.com/build/date.js"></script>

<script>
   (function ()
   {
      document.write(new Date().toString("hh:mm tt"));
   })();
</script>
</html>

回答by Steve Tauber

Here's a way using regex:

这是使用正则表达式的一种方法:

console.log(new Date('7/10/2013 20:12:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, ""))
console.log(new Date('7/10/2013 01:12:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, ""))

This creates 3 matching groups:

这将创建 3 个匹配组:

  • ([\d]+:[\d]{2})- Hour:Minute
  • (:[\d]{2})- Seconds
  • (.*)- the space and period (Period is the official name for AM/PM)
  • ([\d]+:[\d]{2})- 小时:分钟
  • (:[\d]{2})- 秒
  • (.*)- 空格和句号(句号是 AM/PM 的正式名称)

Then it displays the 1st and 3rd groups.

然后显示第 1 组和第 3 组。

WARNING: toLocaleTimeString() may behave differently based on region / location.

警告:toLocaleTimeString() 的行为可能因地区/位置而异。

回答by rattray

If you don't need to print the am/pm, I found the following nice and concise:

如果您不需要打印 am/pm,我发现以下内容简洁明了:

var now = new Date();
var hours = now.getHours() % 12 || 12;  // 12h instead of 24h, with 12 instead of 0. 

This is based off @bbrame's answer.

这是基于@bbrame 的回答。

回答by Edwin Mendez

As far as I know, the best way to achieve that without extensions and complex coding is like this:

据我所知,在没有扩展和复杂编码的情况下实现这一目标的最佳方法是这样的:

     date.toLocaleString([], { hour12: true});

Javascript AM/PM Format

Javascript AM/PM 格式

<!DOCTYPE html>
<html>
<body>
    <p>Click the button to display the date and time as a string.</p>

    <button onclick="myFunction()">Try it</button>
    <button onclick="fullDateTime()">Try it2</button>
    <p id="demo"></p>
    <p id="demo2"></p>
    <script>
        function myFunction() {
            var d = new Date();
            var n = d.toLocaleString([], { hour: '2-digit', minute: '2-digit' });
            document.getElementById("demo").innerHTML = n;
        }
        function fullDateTime() {
            var d = new Date();          
            var n = d.toLocaleString([], { hour12: true});
            document.getElementById("demo2").innerHTML = n;
        }
    </script>
</body>
</html>

I found this checking this question out.

我发现这检查了这个问题。

How do I use .toLocaleTimeString() without displaying seconds?

如何使用 .toLocaleTimeString() 而不显示秒数?

回答by Vijay Maheriya

My suggestion is use moment js for date and time operation.

我的建议是使用 moment js 进行日期和时间操作。

https://momentjs.com/docs/#/displaying/format/

https://momentjs.com/docs/#/displaying/format/

console.log(moment().format('hh:mm a'));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

回答by Krishnamoorthy Acharya

Please find the solution below

请在下面找到解决方案

var d = new Date();
var amOrPm = (d.getHours() < 12) ? "AM" : "PM";
var hour = (d.getHours() < 12) ? d.getHours() : d.getHours() - 12;
return   d.getDate() + ' / ' + d.getMonth() + ' / ' + d.getFullYear() + ' ' + hour + ':' + d.getMinutes() + ' ' + amOrPm;

回答by LiranBo

use dateObj.toLocaleString([locales[, options]])

dateObj.toLocaleString([locales[, options]])

Option 1- Using locales

选项 1- 使用语言环境

var date = new Date();
console.log(date.toLocaleString('en-US'));

Option 2- Using options

选项 2- 使用选项

var options = { hour12: true };
console.log(date.toLocaleString('en-GB', options));

Note:supported on all browsers but safari atm

注意:支持所有浏览器,但 safari atm

回答by mtm

In modern browsers,use Intl.DateTimeFormatand force 12hr format with options:

现代浏览器中,使用Intl.DateTimeFormat并强制使用12 小时格式的选项:

    let now = new Date();

    new Intl.DateTimeFormat('default',
        {
            hour12: true,
            hour: 'numeric',
            minute: 'numeric'
        }).format(now);

    // 6:30 AM

Using defaultwill honor browser's default locale if you add more options, yet will still output 12hr format.

default如果您添加更多选项,使用将遵循浏览器的默认语言环境,但仍会输出 12 小时格式。