如何以12小时格式(AM/PM)显示JavaScript datetime对象?
当前回答
希望这个答案比其他答案更容易理解(尤其是对新手来说)。
以下是我在一些站点中实现的解决方案,用于通知上次修改站点代码的时间。它通过date的选项参数实现AM/PM时间。toLocaleDateString(参见相关的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>
注意:在这个用例中,是文档。lastModified有一些奇怪的行为,这取决于它是在本地运行还是在外部服务器上运行(参见这个堆栈溢出问题)。虽然当我在我的GitHub页面上运行它时,它可以正常工作(你应该在网站的页脚处看到它在运行)。
其他回答
这里有另一种简单有效的方法:
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 -->
en-US的短RegExp:
var d = new Date();
d = d.toLocaleTimeString().replace(/:\d+ /, ' '); // current time, e.g. "1:54 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()而不显示秒?
您可以使用这段简单的代码来确定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';
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>
推荐文章
- 什么时候JavaScript是同步的?
- 从DateTime中提取小时(SQL Server 2005)
- 如何在Typescript中解析JSON字符串
- Javascript reduce()在对象
- 在angularJS中& vs @和=的区别是什么
- 错误"Uncaught SyntaxError:意外的标记与JSON.parse"
- JavaScript中的querySelector和querySelectorAll vs getElementsByClassName和getElementById
- 给一个数字加上st, nd, rd和th(序数)后缀
- 如何以编程方式触发引导模式?
- setTimeout带引号和不带括号的区别
- 在JS的Chrome CPU配置文件中,'self'和'total'之间的差异
- 用javascript检查输入字符串中是否包含数字
- 如何使用JavaScript分割逗号分隔字符串?
- 在Javascript中~~(“双波浪号”)做什么?
- 谷歌chrome扩展::console.log()从后台页面?