Open In App

How to format current date in MM/DD/YYYY HH:MM:SS format using JavaScript ?

Given a date and the task is to format the current date in MM/DD/YYYY HH:MM:SS format. Here are a few of the most techniques discussed with the help of JavaScript. 

Approach 1:



Example: This example implements the above approach. 




<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
  
    <p id="GFG_UP">
    </p>
  
    <button onclick="gfg_Run()">
        Click Here
    </button>
  
    <p id="GFG_DOWN">
    </p>
  
    <script>
        var el_up = document.getElementById("GFG_UP");
        var el_down = document.getElementById("GFG_DOWN");
        var date = new Date();
        el_up.innerHTML = "Click on the button to format"
            + " the date accordingly.<br>Date = " + date;
          
        function gfg_Run() {
            var Str =
                ("00" + (date.getMonth() + 1)).slice(-2)
                + "/" + ("00" + date.getDate()).slice(-2)
                + "/" + date.getFullYear() + " "
                + ("00" + date.getHours()).slice(-2) + ":"
                + ("00" + date.getMinutes()).slice(-2)
                + ":" + ("00" + date.getSeconds()).slice(-2);
                  
            el_down.innerHTML = Str;
        }
    </script>
</body>

Output:



 

Approach 2:

Example: This example implements the above approach. 




<body>
  
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
  
    <p id="GFG_UP">
    </p>
  
    <button onclick="gfg_Run()">
        Click Here
    </button>
  
    <p id="GFG_DOWN">
    </p>
  
    <script>
        var el_up = document.getElementById("GFG_UP");
        var el_down = document.getElementById("GFG_DOWN");
        var d = new Date();
          
        el_up.innerHTML = "Click on the button to format"
                + " the date accordingly.<br>Date = " + d;
        Number.prototype.padding = function(base, chr) {
            var len = (String(base || 10).length
                        - String(this).length) + 1;
                          
            return len > 0 ? new Array(len).join(chr || '0')
                    + this : this;
        }
          
        function gfg_Run() {
            str = [(d.getMonth()+1).padding(),
                    d.getDate().padding(),
                    d.getFullYear()].join('/')
                    + ' ' + [ d.getHours().padding(),
                    d.getMinutes().padding(),
                    d.getSeconds().padding()].join(':');
            el_down.innerHTML = str;
        }
    </script>
</body>

Output:

 


Article Tags :