如何以12小时格式(AM/PM)显示JavaScript datetime对象?
当前回答
如果你只是想显示时间,那么…
var time = new Date(); console.log ( 时间。toLocaleString('en-US',{小时:'数字',小时12:true}) );
输出:早上7点
如果你也想显示会议纪要,那么……
var time = new Date(); console.log ( 时间。toLocaleString('en-US',{小时:'数字',分钟:'数字',小时12:true}) );
输出:早上7:23
其他回答
如果你不需要打印上午/下午,我发现以下内容很好很简洁:
var now = new Date();
var hours = now.getHours() % 12 || 12; // 12h instead of 24h, with 12 instead of 0.
这是基于@bbrame的回答。
试试这个
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var ampm = hours >= 12 ? "pm" : "am";
使用Moment.js
使用moment.js时,请在JavaScript中使用以下代码
H, HH 24 hour time
h, or hh 12 hour time (use in conjunction with a or A)
format()方法以特定格式返回日期。
moment(new Date()).format("YYYY-MM-DD HH:mm"); // 24H clock
moment(new Date()).format("YYYY-MM-DD hh:mm A"); // 12H clock (AM/PM)
moment(new Date()).format("YYYY-MM-DD hh:mm a"); // 12H clock (am/pm)
我的建议是使用moment js进行日期和时间操作。
https://momentjs.com/docs/#/displaying/format/
console.log(时刻)。格式(“hh: mm ')); < script src = " / / cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js " > < /脚本>
<script>
var todayDate = new Date();
var getTodayDate = todayDate.getDate();
var getTodayMonth = todayDate.getMonth()+1;
var getTodayFullYear = todayDate.getFullYear();
var getCurrentHours = todayDate.getHours();
var getCurrentMinutes = todayDate.getMinutes();
var getCurrentAmPm = getCurrentHours >= 12 ? 'PM' : 'AM';
getCurrentHours = getCurrentHours % 12;
getCurrentHours = getCurrentHours ? getCurrentHours : 12;
getCurrentMinutes = getCurrentMinutes < 10 ? '0'+getCurrentMinutes : getCurrentMinutes;
var getCurrentDateTime = getTodayDate + '-' + getTodayMonth + '-' + getTodayFullYear + ' ' + getCurrentHours + ':' + getCurrentMinutes + ' ' + getCurrentAmPm;
alert(getCurrentDateTime);
</script>