如何以12小时格式(AM/PM)显示JavaScript datetime对象?
当前回答
<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>
其他回答
en-US的短RegExp:
var d = new Date();
d = d.toLocaleTimeString().replace(/:\d+ /, ' '); // current time, e.g. "1:54 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 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");
如果你只是想显示时间,那么…
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的回答。
推荐文章
- 错误:'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”错误