如何在12小时AM/PM格式中显示JavaScript datetime ?

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

704149 次浏览

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));

查看Datejs。它们的内置格式化器可以这样做:http://code.google.com/p/datejs/wiki/APIDocumentation#toString

这是一个非常方便的库,特别是如果您打算用date对象做其他事情时。

下面是一种使用regex的方法:

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

这将创建3个匹配组:

  • ([\d]+:[\d]{2})小时:分钟
  • (:[\d]{2}) -秒
  • (.*) -空间和周期(周期是AM/PM的正式名称)

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

警告:toLocaleTimeString()可能会根据区域/位置表现不同。

en-US的短RegExp:

var d = new Date();
d = d.toLocaleTimeString().replace(/:\d+ /, ' '); // current time, e.g. "1:54 PM"

这里有另一种简单有效的方法:

        var d = new Date();


var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";


var month = new Array(11);
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";


var t = d.toLocaleTimeString().replace(/:\d+ /, ' ');


document.write(weekday[d.getDay()] + ',' + " " + month[d.getMonth()] + " " + d.getDate() + ',' + " " + d.getFullYear() + '<br>' + d.toLocaleTimeString());


</script></div><!-- #time -->

如果你不需要打印上午/下午,我发现以下内容很好很简洁:

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

这是基于@bbrame的回答。

或者只是简单地执行以下代码:

    <script>
time = function() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt_clock').innerHTML = h + ":" + m + ":" + s;
var t = setTimeout(function(){time()}, 0);
}


time2 = function() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
if (h>12) {
document.getElementById('txt_clock_stan').innerHTML = h-12 + ":" + m + ":" + s;
}
var t = setTimeout(function(){time2()}, 0);
}


time3 = function() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
if (h>12) {
document.getElementById('hour_line').style.width = h-12 + 'em';
}
document.getElementById('minute_line').style.width = m + 'em';
document.getElementById('second_line').style.width = s + 'em';
var t = setTimeout(function(){time3()}, 0);
}


checkTime = function(i) {
if (i<10) {i = "0" + i};  // add zero in front of numbers < 10
return i;
}
</script>

我发现它是在这里它工作正常。

var date_format = '12'; /* FORMAT CAN BE 12 hour (12) OR 24 hour (24)*/
 

 

var d       = new Date();
var hour    = d.getHours();  /* Returns the hour (from 0-23) */
var minutes     = d.getMinutes();  /* Returns the minutes (from 0-59) */
var result  = hour;
var ext     = '';
 

if(date_format == '12'){
if(hour > 12){
ext = 'PM';
hour = (hour - 12);
result = hour;


if(hour < 10){
result = "0" + hour;
}else if(hour == 12){
hour = "00";
ext = 'AM';
}
}
else if(hour < 12){
result = ((hour < 10) ? "0" + hour : hour);
ext = 'AM';
}else if(hour == 12){
ext = 'PM';
}
}
 

if(minutes < 10){
minutes = "0" + minutes;
}
 

result = result + ":" + minutes + ' ' + ext;
 

console.log(result);

和活塞例子在这里

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

选项1 -使用区域设置

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

选项2 -使用选项

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

注意:支持除safari atm以外的所有浏览器

如果你只是想显示时间,那么…

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

输出:早上7点

如果你也想显示会议纪要,那么……

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

输出:早上7:23

您可以使用这段简单的代码来确定am或PM

var today=new Date();
var noon=new Date(today.getFullYear(),today.getMonth(),today.getDate(),12,0,0);
var ampm = (today.getTime()<noon.getTime())?'am':'pm';

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

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

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>

我查这个问题时发现的。

我如何使用。tolocaletimestring()不显示秒?< / >

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

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>

一个简短而甜蜜的实现:

// returns date object in 12hr (AM/PM) format
var formatAMPM = function formatAMPM(d) {
var h = d.getHours();
return (h % 12 || 12)
+ ':' + d.getMinutes().toString().padStart(2, '0')
+ ' ' + (h < 12 ? 'A' : 'P') + 'M';
};

var d = new Date();
var hours = d.getHours() % 12;
hours = hours ? hours : 12;
var test = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][(d.getMonth() + 1)] + " " +
("00" + d.getDate()).slice(-2) + " " +
d.getFullYear() + " " +
("00" + hours).slice(-2) + ":" +
("00" + d.getMinutes()).slice(-2) + ":" +
("00" + d.getSeconds()).slice(-2) + ' ' + (d.getHours() >= 12 ? 'PM' : 'AM');
    

document.getElementById("demo").innerHTML = test;
<p id="demo" ></p>

<h1 id="clock_display" class="text-center" style="font-size:40px; color:#ffffff">[CLOCK TIME DISPLAYS HERE]</h1>






<script>
var AM_or_PM = "AM";


function startTime(){


var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();


h = twelve_hour_time(h);
m = checkTime(m);
s = checkTime(s);






document.getElementById('clock_display').innerHTML =
h + ":" + m + ":" + s +" "+AM_or_PM;
var t = setTimeout(startTime, 1000);


}


function checkTime(i){


if(i < 10){
i = "0" + i;// add zero in front of numbers < 10
}
return i;
}


// CONVERT TO 12 HOUR TIME. SET AM OR PM
function twelve_hour_time(h){


if(h > 12){
h = h - 12;
AM_or_PM = " PM";
}
return h;


}


startTime();


</script>
<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>

下面是解决方案

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;

为此使用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)

这是我的解决方案

function getTime() {
var systemDate = new Date();
var hours = systemDate.getHours();
var minutes = systemDate.getMinutes();
var strampm;
if (hours >= 12) {
strampm= "PM";
} else {
strampm= "AM";
}
hours = hours % 12;
if (hours == 0) {
hours = 12;
}
_hours = checkTimeAddZero(hours);
_minutes = checkTimeAddZero(minutes);
console.log(_hours + ":" + _minutes + " " + strampm);
}


function checkTimeAddZero(i) {
if (i < 10) {
i = "0" + i
}
return i;
}

试试这个

      var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var ampm = hours >= 12 ? "pm" : "am";
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();


if (month.toString().length == 1) {
month = '0' + month;
}
if (day.toString().length == 1) {
day = '0' + day;
}


var hours = now.getHours();
var minutes = now.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
var timewithampm = hours + ':' + minutes + ' ' + ampm;


var dateTime = monthNames[parseInt(month) - 1] + ' ' + day + ' ' + year + ' ' + timewithampm;
return dateTime;
}

现代浏览器,中使用Intl.DateTimeFormat和强制12hr格式,并带有选项:

    let now = new Date();


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


// 6:30 AM

如果您添加更多选项,则使用default将尊重浏览器的默认区域,但仍将输出12小时的格式。

它将返回如下格式

09:56 AM

如果小时数小于10,则在start中添加0

这里使用的是ES6语法

const getTimeAMPMFormat = (date) => {
let hours = date.getHours();
let minutes = date.getMinutes();
const ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
hours = hours < 10 ? '0' + hours : hours;
// appending zero in the start if hours less than 10
minutes = minutes < 10 ? '0' + minutes : minutes;
return hours + ':' + minutes + ' ' + ampm;
};
console.log(getTimeAMPMFormat(new Date)); // 09:59 AM

function formatTime( d = new Date(), ampm = true )
{
var hour = d.getHours();
    

if ( ampm )
{
var a = ( hour >= 12 ) ? 'PM' : 'AM';
hour = hour % 12;
hour = hour ? hour : 12; // the hour '0' should be '12'
}


var hour    = checkDigit(hour);
var minute  = checkDigit(d.getMinutes());
var second  = checkDigit(d.getSeconds());
  

// https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascript
return ( ampm ) ? `${hour}:${minute}:${second} ${a}` : `${hour}:${minute}:${second}`;
}


function checkDigit(t)
{
return ( t < 10 ) ? `0${t}` : t;
}


document.querySelector("#time1").innerHTML = formatTime();
document.querySelector("#time2").innerHTML = formatTime( new Date(), false );
<p>ampm true:   <span id="time1"></span> (default)</p>
<p>ampm false:  <span id="time2"></span></p>

更新以获得更多压缩

const formatAMPM = (date) => {
let hours = date.getHours();
let minutes = date.getMinutes();
const ampm = hours >= 12 ? 'pm' : 'am';


hours %= 12;
hours = hours || 12;
minutes = minutes < 10 ? `0${minutes}` : minutes;


const strTime = `${hours}:${minutes} ${ampm}`;


return strTime;
};


console.log(formatAMPM(new Date()));
   const formatAMPM = (date) => {
try {
let time = date.split(" ");
let hours = time[4].split(":")[0];
let minutes = time[4].split(":")[1];
hours = hours || 12;
const ampm = hours >= 12 ? " PM" : " AM";
minutes = minutes < 10 ? `${minutes}` : minutes;
hours %= 12;
const strTime = `${hours}:${minutes} ${ampm}`;
return strTime;
} catch (e) {
return "";
}
};


const startTime = "2021-12-07T17:00:00.073Z"
formatAMPM(new Date(startTime).toUTCString())

这是最简单的方法,你可以实现这使用三元操作符,或者你也可以使用if else代替!

const d = new Date();
let hrs = d.getHours();
let m = d.getMinutes();
// Condition to add zero before minute
let min = m < 10 ? `0${m}` : m;
const currTime = hrs >= 12 ? `${hrs - 12}:${min} pm` : `${hrs}:${min} am`;
console.log(currTime);

希望这个答案比其他答案更容易理解(尤其是对新手来说)。

以下是我在一些站点中实现的解决方案,用于通知上次修改站点代码的时间。它通过date.toLocaleDateStringoptions参数实现AM/PM时间(与看到相关的Mozilla文档)。

// Last time page code was updated/changed
const options = {
year: "numeric",
month: "long",
weekday: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: true // This is the line of code we care about here
/*
false: displays 24hs format for time
true: displays 12, AM and PM format
*/
};


let last = document.lastModified;
let date = new Date(last);
let local = date.toLocaleDateString("en-US", options);
let fullDate = `${local}`;
document.getElementById("updated").textContent = fullDate;

输出的格式是:

Saturday, May 28, 2022, 8:38:50 PM

该输出然后显示在以下HTML代码中:

<p>Last update: <span id="updated">_update_date_goes_here</span></p>

注意:在这个用例中,document.lastModified有一些奇怪的行为,这取决于它是在本地运行还是在外部服务器上运行(看到这个堆栈溢出问题)。虽然当我在我的GitHub页面上运行它时,它可以正确地工作(你应该在页脚的站点上看到它的动作)。

如果你有时间作为字符串像这样var myTime = "15:30", 然后你可以使用下面的代码得到am pm.

var hour = parseInt(myTime.split(":")[0]) % 12;
var timeInAmPm = (hour == 0 ? "12": hour ) + ":" + myTime.split(":")[1] + " " + (parseInt(parseInt(myTime.split(":")[0]) / 12) < 1 ? "am" : "pm");

function startTime() {
const today = new Date();
let h = today.getHours();
let m = today.getMinutes();
let s = today.getSeconds();
var meridian = h >= 12 ? "PM" : "AM";
h = h % 12;
h = h ? h : 12;
m = m < 10 ? "0" + m : m;
s = s < 10 ? "0" + s : s;
var strTime = h + ":" + m + ":" + s + " " + meridian;
document.getElementById('time').innerText = strTime;
setTimeout(startTime, 1000);
}


startTime();
<h1 id='time'></h1>