-2

I am new to coding and need a little help. I found a clock javascript and I am trying to change the time format to the 12-hour format. How can I modify the code below to run on the 12-hour format?

function updateTime(){
        var currentTime = new Date()
        var hour = pad( currentTime.getHours(), 2);
        var minutes = pad( currentTime.getMinutes(), 2);
        var hour_1 = hour.substr(0,1);
        var hour_2 = hour.substr(1,2);
        var minute_1 = minutes.substr(0,1);
        var minute_2 = minutes.substr(1,2);

Thanks in advance for any help/comments.

  • 2
    This should help: http://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format – Rajesh Mar 15 '17 at 12:57
  • 2
    Possible duplicate of [Conversion 12-hour to 24-hour format with javascript](http://stackoverflow.com/questions/41338194/conversion-12-hour-to-24-hour-format-with-javascript) – codemacabre Mar 15 '17 at 13:01
  • 2
    Possible duplicate of [How do you display javascript datetime in 12 hour AM/PM format?](http://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format) – Kursad Gulseven Mar 15 '17 at 13:06
  • I looked at these links prior to posting. I tried what was suggested in each one, and none of the worked. – Doug Chester Mar 16 '17 at 17:00

2 Answers2

1

Use moment js for any date operations.

console.log(moment().format('hh:mm a'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Vijay Maheriya
  • 1,617
  • 16
  • 21
1

I would also recommend a good date formatting library. However, if you are new to programming and want to learn how to do it yourself you could also use a modulo operator.

currentTime.getHours() % 12

The modulo operator (%) gives the remainder of a integer division.

Remq
  • 378
  • 1
  • 3
  • 9