'show real time clock on html using javascript

can someone help me with this code, I'm really bad using JS

I want to show only Brazil time in the application, regardless of where the user accesses the application.

<head>
    <script>
        function display_c() {
            var refresh = 1000; // Refresh rate in milli seconds
            mytime = setTimeout('display_ct()', refresh)
        }

        function display_ct() {
            var strcount
            var x = new Date().toLocaleString("en-US", {timeZone: "America/Sao_Paulo"});
            var x1 = x.getMonth() + 1 + "/" + x.getDate() + "/" + x.getYear();
            x1 = x1 + " - " + x.getHours( ) + ":" + x.getMinutes() + ":" + x.getSeconds();
            document.getElementById('ct').innerHTML = x1;

            tt = display_c();
        }
    </script>
</head>

<body onload=display_ct();>
    <span id='ct' ></span>
</body>

Error

painel:48 Uncaught TypeError: x.getMonth is not a function
at display_ct (painel:48)
at onload (painel:57)


Solution 1:[1]

This code will do what you want. Your problem was that you used toLocaleString on your x variable and then tried to use the getMonth() method on it. However, that variable is no longer a date; when you use toLocaleString you turn it into a String. The local string, by default, is formatted almost how you like it. I only had to change a little bit to use the dash in between the date and time instead of the default comma.

var timeDisplay = document.getElementById("time");


function refreshTime() {
  var dateString = new Date().toLocaleString("en-US", {timeZone: "America/Sao_Paulo"});
  var formattedString = dateString.replace(", ", " - ");
  timeDisplay.innerHTML = formattedString;
}

setInterval(refreshTime, 1000);
<p id="time"></p>

Solution 2:[2]

    // Inside your Javascript file
    function startTime() {
        var today = new Date();
        var h = today.getHours();
        var m = today.getMinutes();
        var s = today.getSeconds();
        m = checkTime(m);
        s = checkTime(s);
        document.getElementById('txt').innerHTML =
        h + ":" + m + ":" + s;
        var t = setTimeout(startTime, 500);
    }
    function checkTime(i) {
        if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
        return i;
    }
    
    <!-- Inside your HTML file -->
    <body onload="startTime()">
         <div id="txt"></div>
    </body>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael Karpinski
Solution 2