简体   繁体   中英

Change the js time format from 24hr to 12hr

I have already asked a quesion How to hide time standards from javascript

but i need to change time format to 12 hr.

 function display_c() { var refresh = 1000; // Refresh rate in milli seconds mytime = setTimeout('display_ct()', refresh) } function display_ct() { var strcount var x = new Date() document.getElementById('ct').innerHTML = x.toString().replace(/GMT(.*)/g,""); tt = display_c(); } display_ct() 
 <span id='ct'></span> 

Match the hours with regex pattern /(\\d+)(:)/ and check > 12 Then apply the condition.

Date methods

 function display_c() { var refresh = 1000; // Refresh rate in milli seconds mytime = setTimeout('display_ct()', refresh) } var format; function display_ct() { var strcount var x = new Date() document.getElementById('ct').innerHTML = x.toString().replace(/GMT(.*)/g, "").replace(/(\\d+)(:)/, function(a, b, c) { b = parseInt(b); if (b > 12) { b = b - 12; format ='PM'; } else{ b=b; format="AM"; } return b + c; })+format; tt = display_c(); } display_ct() 
 <span id='ct'></span> 

Or try with another model

 function display_c() { var refresh = 1000; // Refresh rate in milli seconds mytime = setTimeout('display_ct()', refresh) } var m =['Jan','Feb','Mar','Aprl','May','Jun','July','Aug','Sep','Oct','Nov','Dec']; var w =['Sun','Mon','Tue','Wed','Thu','Fri','Sat']; function display_ct() { var strcount var x = new Date() var h = x.getHours() > 12 ? x.getHours() -12 : x.getHours(); var format = x.getHours() > 12 ? 'PM' : 'AM'; document.getElementById('ct').innerHTML =w[x.getDay()]+' '+m[x.getMonth()]+' '+x.getFullYear()+' '+h+':'+x.getMinutes()+':'+x.getSeconds()+' '+format; tt = display_c(); } display_ct() 
 <span id='ct'></span> 

You can do that using momentjs string format. Using this you can display the date in the way you like.

In the below snippet you can see how to achieve same functionality.

 function display_c() { var refresh = 1000; // Refresh rate in milli seconds mytime = setTimeout('display_ct()', refresh) } function display_ct() { var strcount var x = new Date() document.getElementById('ct').innerHTML = moment(x).format('ddd MMM DD gggg hh:mm:ss'); tt = display_c(); } display_ct() 
 <script src="http://momentjs.com/downloads/moment.js"></script> <span id='ct'></span> 

Note:

  1. hh is for 12 hours format , you can find more formats accesing the documentation (you can see some that I used in my example).

  2. The nice thing about this is that remove the need of using replace .

  3. And it follows the KISS principle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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