Venoox
Venoox

Reputation: 66

Digits with leading zero in date and time

I found this Javascript script online which refreshes the time every second and displays it. I want the program to display digits with leading zero. Currently it's showing 6/8/2017 - 19:8:54 but I want it to show 06/08/2017 - 19:08:54.

<script type="text/javascript"> 
    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()
        var x1=x.getDate() + "/" + x.getMonth() + "/" + x.getYear(); 
        x1 = x1 + " - " + x.getHours( )+ ":" + x.getMinutes() + ":" + 
        x.getSeconds();
        document.getElementById('ct').innerHTML = x1;

        tt=display_c();
    }
</script>

Upvotes: 0

Views: 331

Answers (1)

Koby Douek
Koby Douek

Reputation: 16693

You can use the following:

var x1 =   ('0' + x.getDate()).slice(-2)      + '/'
         + ('0' + (x.getMonth()+1)).slice(-2) + '/'
         + x.getFullYear()                    + '-'
         + ('0' + x.getHours()).slice(-2)     + ':'
         + ('0' + x.getMinutes()).slice(-2)   + ':' 
         + ('0' + x.getSeconds()).slice(-2);

Upvotes: 1

Related Questions