How to get datetime in JavaScript?

Solution 1:

Semantically, you're probably looking for the one-liner

new Date().toLocaleString()

which formats the date in the locale of the user.

If you're really looking for a specific way to format dates, I recommend the moment.js library.

Solution 2:

If the format is "fixed" meaning you don't have to use other format you can have pure JavaScript instead of using whole library to format the date:

//Pad given value to the left with "0"
function AddZero(num) {
    return (num >= 0 && num < 10) ? "0" + num : num + "";
}

window.onload = function() {
    var now = new Date();
    var strDateTime = [[AddZero(now.getDate()), 
        AddZero(now.getMonth() + 1), 
        now.getFullYear()].join("/"), 
        [AddZero(now.getHours()), 
        AddZero(now.getMinutes())].join(":"), 
        now.getHours() >= 12 ? "PM" : "AM"].join(" ");
    document.getElementById("Console").innerHTML = "Now: " + strDateTime;
};
<div id="Console"></div>

The variable strDateTime will hold the date/time in the format you desire and you should be able to tweak it pretty easily if you need.

I'm using join as good practice, nothing more, it's better than adding strings together.

Solution 3:

var now = new Date();

now.format("dd/MM/yyyy hh:mm TT");

Get full details here: Flagrant Badassery » JavaScript Date Format

Solution 4:

Date().toLocaleString() returns this: 7/31/2018, 12:58:03 PM

Pretty close - just drop the comma and the seconds:

new Date().toLocaleString().replace(",","").replace(/:.. /," ");

Results: 7/31/2018 12:58 PM