1

I have simple code for 12hr format time

// This function gets the current time and injects it into the DOM
      function updateClock() {
                // Gets the current time
                var now = new Date();

                // Get the hours, minutes and seconds from the current time
                var hours = now.getHours();
                var minutes = now.getMinutes();
                var seconds = now.getSeconds();


                // Format hours, minutes and seconds
                if (hours > 12) {
                    hours = hours - 12;
                }
                if (minutes < 10) {
                    minutes = "0" + minutes;
                }
                if (seconds < 10) {
                    seconds = "0" + seconds;
                }

                // Gets the element we want to inject the clock into
                var elem = document.getElementById('clock');

                // Sets the elements inner HTML value to our clock data
                elem.innerHTML = hours + ':' + minutes + ':' + seconds ;
            }

I want to add AM/PM please help me thanks in advance Im just beginner on javascript

3 Answers3

3

After editting your own code:

        // Get the hours, minutes and seconds from the current time
        var hours = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds();
        var amOrPm = 'AM';

        // Format hours, minutes and seconds
        if (hours > 12) {
            amOrPm = 'PM';
            hours = hours - 12;
        }
        if (minutes < 10) {
            minutes = "0" + minutes;
        }
        if (seconds < 10) {
            seconds = "0" + seconds;
        }

        // Gets the element we want to inject the clock into
        var elem = document.getElementById('clock');

        // Sets the elements inner HTML value to our clock data
        elem.innerHTML = hours + ':' + minutes + ':' + seconds + ' ' + amOrPm;
Mustafa Ehsan Alokozay
  • 5,583
  • 2
  • 24
  • 30
1

Try this...

 var ampm = hours >= 12 ? 'pm' : 'am';

then

elem.innerHTML = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
Sankar
  • 6,908
  • 2
  • 30
  • 53
0

I don't know if you want to code it by yourself, but there is a really really great library which handles everything with date stuff you can imagine.

Just checkout momentjs. It's an easy AF lib to transform dates (also in pm/am).

If you've any question :) just comment ...

Michael J. Zoidl
  • 1,708
  • 16
  • 13