12 to 24 hour format in JavaScript

4

I have a digital clock in JavaScript that is printing time from 1/12. 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're printing 5:19:51 PM at 17:19.

    
asked by anonymous 23.03.2016 / 21:22

1 answer

3

This .toLocaleTimeString() method accepts arguments. The first is Locale (the desired country code, the second is an option object. Then you can set the option hour12 which can be true or false .

Different countries have different predefined modes, so you'll have to test and define which ones you want. In 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 default, ie hour12: true is hours in 12-hour 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: link

    
23.03.2016 / 21:28