PHP and Javascript Clock Formatting

I took this code from PHP with javascript code, live clock and successfully posted it on my website. The code is here:

<?php function d1() { $time1 = time(); $date1 = date("h:i:sa",$time1); echo $date1; } ?> <script> var now = new Date(<?php echo time() * 1000 ?>); function startInterval(){ setInterval('updateTime();', 1000); } startInterval();//start it right away function updateTime(){ var nowMS = now.getTime(); nowMS += 1000; now.setTime(nowMS); var clock = document.getElementById('qwe'); if(clock){ clock.innerHTML = now.toTimeString();//adjust to suit } } </script> <div id="qwe"></div> 

However, the time format is displayed as follows:

 21:41:44 GMT-0400 (Eastern Standard Time) 

I want it to display as

 9:41:44 PM 

I assume this line

  clock.innerHTML = now.toTimeString();//adjust to suit 

- this is the one I need to change, but I can not find any formats that show it very simply. Do I need to write something myself to show it in this custom format?

+4
source share
2 answers

I want to suggest that you try using the developer tools in Chrome so that you can learn what properties and features are available for the object.

Try this, F12 in the developer tool and there enter

 var date_new = new Date() 

then enter date_new. after clicking this point, you will see what potential functions are available to you.

enter image description here

Of course, it is useful to read the official documentation to know everything about it, but if you do not have an Internet connection, or hurry. you can just take a look at those functions of the Date object.

Have fun coding!

+5
source

You can try and do something like this.

 function formatTime(date) { var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); var ampm = hours >= 12 ? 'PM' : 'AM'; hours = hours % 12; hours = hours ? hours : 12; minutes = minutes < 10 ? '0'+minutes : minutes; return hours + ':' + minutes + ':' + seconds + ' ' + ampm; } // your existing code with modification ... clock.innerHTML = formatTime(now);//adjust to suit ... 

If you work too much with a date and need to use functions such as described above, you should consider using momentjs .

+1
source