Javascript 12 to 24 hour format

Asked

Viewed 1,711 times

4

I have a digital Javascript clock that is printing 1/12 hours. How to convert to 13/24.

 <script>
    function relogio()
    {
    var d = new Date()
    var t = d.toLocaleTimeString()
    document.getElementById('relogio').innerHTML = t
    }
    setInterval(function(){relogio()},1000)
</script> 

You are printing 5:19:51 PM at 5:19 PM.

  • In which browser? I made a test here and is printing in the format you want..

  • Both Chrome and Firefox, MAC OS system. On the system is right.

1 answer

3


That method .toLocaleTimeString() takes arguments. The first is Locale (the code of the desired country, the second is an option object. There you can clear the option hour12 which may be true or false.

Different countries have different predetermined modes, port that you’ll have to test and define which ones you want. On MDN says so:

Whether to use 12-hour time (as opposed to 24-hour time). Possible values are true and false; the default is locale dependent.

I believe that pt-PT and pt-BR have the same foreknowledge, that is to say hour12: true is 12 hours in format (with AM and PM).

Example:

<script>
    function relogio(){
        var d = new Date();
        var t = d.toLocaleTimeString('pt-PT', {hour12: false});
        document.getElementById('relogio').innerHTML = t;
    }
    setInterval(relogio, 1000);
</script> 

jsFiddle: https://jsfiddle.net/1zf9x752/

  • 1

    Thank you Sergio and Marllon Nasser.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.