How to Display JavaScript Datetime in 12 Hour Am/Pm Format

How do you display JavaScript datetime in 12 hour AM/PM format?

function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}

console.log(formatAMPM(new Date));

How to get current time in a format hh:mm AM/PM in Javascript?

Use Date methods to set and retrieve time and construct a time string, something along the lines of the snippet.

[edit] Just for fun: added a more generic approach, using 2 Date.prototype extensions.

var now = new Date();now.setHours(now.getHours()+2);var isPM = now.getHours() >= 12;var isMidday = now.getHours() == 12;var result = document.querySelector('#result');var time = [now.getHours() - (isPM && !isMidday ? 12 : 0),             now.getMinutes(),             now.getSeconds() || '00'].join(':') +           (isPM ? ' pm' : 'am');            result.innerHTML = 'the current time plus two hours = '+ time;
// a more generic approach: extend DateDate.prototype.addTime = addTime;Date.prototype.showTime = showTime;
result.innerHTML += '<h4>using Date.prototype extensions</h4>';result.innerHTML += 'the current time plus twenty minutes = '+ new Date().addTime({minutes: 20}).showTime();result.innerHTML += '<br>the current time plus one hour and twenty minutes = '+ new Date().addTime({hours: 1, minutes: 20}).showTime();result.innerHTML += '<br>the current time <i>minus</i> two hours (format military) = '+ new Date().addTime({hours: -2}).showTime(true);result.innerHTML += '<br>the current time plus ten minutes (format military) = '+ new Date().addTime({minutes: 10}).showTime(true);

function addTime(values) { for (var l in values) { var unit = l.substr(0,1).toUpperCase() + l.substr(1); this['set' + unit](this['get' + unit]() + values[l]); } return this;}
function showTime(military) { var zeroPad = function () { return this < 10 ? '0' + this : this; }; if (military) { return [ zeroPad.call(this.getHours()), zeroPad.call(this.getMinutes()), zeroPad.call(this.getSeconds()) ].join(':'); } var isPM = this.getHours() >= 12; var isMidday = this.getHours() == 12; return time = [ zeroPad.call(this.getHours() - (isPM && !isMidday ? 12 : 0)), zeroPad.call(this.getMinutes()), zeroPad.call(this.getSeconds()) ].join(':') + (isPM ? ' pm' : ' am');
}
<div id="result"></div>

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

UPDATE 2: without seconds option

UPDATE: AM after noon corrected, tested: http://jsfiddle.net/aorcsik/xbtjE/

I created this function to do this:

function formatDate(date) {  var d = new Date(date);  var hh = d.getHours();  var m = d.getMinutes();  var s = d.getSeconds();  var dd = "AM";  var h = hh;  if (h >= 12) {    h = hh - 12;    dd = "PM";  }  if (h == 0) {    h = 12;  }  m = m < 10 ? "0" + m : m;
s = s < 10 ? "0" + s : s;
/* if you want 2 digit hours: h = h<10?"0"+h:h; */
var pattern = new RegExp("0?" + hh + ":" + m + ":" + s);
var replacement = h + ":" + m; /* if you want to add seconds replacement += ":"+s; */ replacement += " " + dd;
return date.replace(pattern, replacement);}
alert(formatDate("February 04, 2011 12:00:00"));

How To Get Time And Date Format In 12 Hour?

You can Try this

 function format_time(date_obj) {
// formats a javascript Date object into a 12h AM/PM time string
var hour = date_obj.getHours();
var minute = date_obj.getMinutes();
var amPM = (hour > 11) ? "pm" : "am";
if(hour > 12) {
hour -= 12;
} else if(hour == 0) {
hour = "12";
}
if(minute < 10) {
minute = "0" + minute;
}
return hour + ":" + minute + amPM;
}

How to get AM or PM?

Try below code:

$('#btnToronto').click(function () {
var hours = new Date().getHours();
var hours = (hours+24-2)%24;
var mid='am';
if(hours==0){ //At 00 hours we need to show 12 am
hours=12;
}
else if(hours>12)
{
hours=hours%12;
mid='pm';
}
alert ('Toronto time: ' + hours + mid);
});

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

Nothing built in, my solution would be as follows :

function tConvert (time) {
// Check correct time format and split into components
time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];

if (time.length > 1) { // If time format correct
time = time.slice (1); // Remove full string match value
time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
time[0] = +time[0] % 12 || 12; // Adjust hours
}
return time.join (''); // return adjusted time or original string
}

tConvert ('18:00:00');

This function uses a regular expression to validate the time string and to split it into its component parts. Note also that the seconds in the time may optionally be omitted.
If a valid time was presented, it is adjusted by adding the AM/PM indication and adjusting the hours.

The return value is the adjusted time if a valid time was presented or the original string.

Working example

(function() {
function tConvert(time) { // Check correct time format and split into components time = time.toString().match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
if (time.length > 1) { // If time format correct time = time.slice(1); // Remove full string match value time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM time[0] = +time[0] % 12 || 12; // Adjust hours } return time.join(''); // return adjusted time or original string }
var tel = document.getElementById('tests');
tel.innerHTML = tel.innerHTML.split(/\r*\n|\n\r*|\r/).map(function(v) { return v ? v + ' => "' + tConvert(v.trim()) + '"' : v; }).join('\n');})();
<h3>tConvert tests : </h3><pre id="tests">  18:00:00  18:00  00:00  11:59:01  12:00:00  13:01:57  24:00  sdfsdf  12:61:54</pre>


Related Topics



Leave a reply



Submit