javascript date to 12 hour time code example
Example 1: js get time in am
var time = new Date();
console.log(
time.toLocaleString('en-US', { hour: 'numeric', hour12: true })
);
Example 2: get the current date time in javascript in 12 hour format
const today = new Date(new Date().toLocaleString("en-US", {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: true
}));
Example 3: js get time in am
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
console.log(formatAMPM(new Date));
Example 4: javascript get 24 hour time
var options = { hour12: false };
console.log(date.toLocaleString('en-US', options));