简体   繁体   English

如何将AM和PM添加24小时到12小时的时间戳?

[英]How to i add 24 hours to 12 hours timestamp with AM and PM?

I made below code for getting real time. 我做了下面的代码以获取实时。 but i don't understand, how to i add timestamp 24 hours to 12 hours and AM PM. 但是我不明白,我该如何添加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); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="time"></div> 

 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> 

You can use momentjs and format using format("hh:mm:ss a") 您可以使用momentjs并使用format("hh:mm:ss a")进行format("hh:mm:ss a")

You can follow this approach ( comments inline ) 您可以遵循这种方法( 内联注释

 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> 

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM