如何以12小时格式(AM/PM)显示JavaScript datetime对象?
当前回答
如果你不需要打印上午/下午,我发现以下内容很好很简洁:
var now = new Date();
var hours = now.getHours() % 12 || 12; // 12h instead of 24h, with 12 instead of 0.
这是基于@bbrame的回答。
其他回答
函数formatAMPM(date) { var hours = date.getHours(); var minutes = date.getMinutes(); Var ampm =小时>= 12 ?'pm': 'am'; 小时=小时% 12; 小时=小时?时长:12小时;//小时'0'应该是'12' 分钟=分钟< 10 ?'0'+minutes: minutes; var strTime = hours + ':' + minutes + ' + ampm; 返回strTime; } console.log (formatAMPM(新日期));
en-US的短RegExp:
var d = new Date();
d = d.toLocaleTimeString().replace(/:\d+ /, ' '); // current time, e.g. "1:54 PM"
如果你把时间设置为字符串,输入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");
它将返回如下格式
09:56 AM
如果小时数小于10,则在start中添加0
这里使用的是ES6语法
const getTimeAMPMFormat = (date) => { let hours = date. gehours (); let minutes = date.getMinutes(); Const ampm =小时>= 12 ?' pm ': ' am '; 小时=小时% 12; 小时=小时?时长:12小时;//小时'0'应该是'12' 小时=小时< 10 ?'0' + hours:小时; //如果hours小于10,则在开始时添加0 分钟=分钟< 10 ?'0' + minutes: minutes; 返回小时+ ':' +分钟+ ' ' + ampm; }; console.log (getTimeAMPMFormat(新日期));// 09:59 am
据我所知,在不进行扩展和复杂编码的情况下实现这一目标的最佳方式是这样的:
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()而不显示秒?
推荐文章
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- 如何解析unix时间戳到时间。时间
- src和dist文件夹的作用是什么?
- 如何使用yyyyMMddHHmmss格式格式化当前时间?
- jQuery UI对话框-缺少关闭图标
- SQL Developer只返回日期,而不是时间。我怎么解决这个问题?
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 在mongodb中存储日期/时间的最佳方法
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误