//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.
// Can also be used as a standalone function
dateFormat(new Date(), "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
dateFormat(new Date(),"dddd d mmmm yyyy")
//Monday 2 June 2014"
function getNowDateTimeStr(){
var now = new Date();
var hour = now.getHours() - (now.getHours() >= 12 ? 12 : 0);
return [[AddZero(now.getDate()), AddZero(now.getMonth() + 1), now.getFullYear()].join("/"), [AddZero(hour), AddZero(now.getMinutes())].join(":"), now.getHours() >= 12 ? "PM" : "AM"].join(" ");
}
//Pad given value to the left with "0"
function AddZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours()+':'+today.getMinutes()+':'+today.getSeconds();
console.log(date + ' '+ time);
var jsonDate = (new Date()).toJSON(); // "2021-08-16T16:31:53.596Z"
var localeDateTime = (new Date()).toLocaleString(); // "8/16/2021, 11:40:57 AM"
var localeDate = (new Date()).toLocaleDateString(); // "8/16/2021"
var localeTime = (new Date()).toLocaleTimeString(); // "11:37:13 AM"
console.log(jsonDate);
console.log(localeDateTime);
console.log(localeDate);
console.log(localeTime);