我在下面的代码中获取实时信息。但我不明白,如何在24小时到12小时和AM PM之间添加时间戳。
setInterval(function() {
var date = new Date();
var hours = date.getHours();
var seconds = date.getSeconds();
var minutes = date.getMinutes();
var realTime = (hours < 10 ? '0' : '') + hours + ':' + (minutes < 10 ? '0' : '') + minutes + ':' + (seconds < 10 ? '0' : '') + seconds
$('#time').html(realTime);
}, 1000);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time"></div>
&#13;
答案 0 :(得分:2)
setInterval(function() {
var now = moment().format("hh:mm:ss a");
$('#time').html(now);
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time"></div>
您可以使用momentjs并使用format("hh:mm:ss a")
答案 1 :(得分:2)
您可以遵循此方法(评论内联)
setInterval(function() {
var date = new Date();
var hours = date.getHours();
var seconds = ("0" + date.getSeconds()).slice(-2);
var minutes = ("0" + date.getMinutes()).slice(-2);
var amPM = hours < 12 ? "AM": "PM"; //decides if this is AM or PM based on hours value
hours = ("0" + (hours % 12)).slice(-2); //pad 0 prefix
var realTime = hours + ':' + minutes + ':' + seconds + " " + amPM; //prepare the date format
$('#time').html(realTime);
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time"></div>
答案 2 :(得分:0)
setInterval(function() {
var date = new Date();
var hours = date.getHours();
var seconds = date.getSeconds();
var minutes = date.getMinutes();
if (hours > 12){hours = hours -12; amPM = ' PM'}else{amPM = ' AM'}
var realTime = (hours < 10 ? '0' : '') + hours + ':' + (minutes < 10 ? '0' : '') + minutes + ':' + (seconds < 10 ? '0' : '') + seconds + amPM
$('#time').html(realTime);
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time"></div>