I want to display Time in 12 hour format by altering the following code. i Tried Various Techniques but no luck, hope to find The solution from u guys .
<
DEMO
function getTime() {
var date = new Date(),
hour = date.getHours();
// var dd = "AM";
var h = hour;
if (h > 12) {
h = hour-12;
// dd = "PM";
}
if (h == 0) {
h = 12;
}
return {
day: days[date.getDay()],
date: date.getDate(),
month: months[date.getMonth()],
hour: appendZero(h),
minute: appendZero(date.getMinutes()),
// dd: dd
};
}
function refreshClock() {
var now = getTime();
$('#date').html(now.day + "<br>" + now.date + '. ' + now.month);
// $('#time').html(now.hour + ":" + now.minute+" "+now.dd);
$('#time').html(now.hour + ":" + now.minute);
setTimeout(function() {
refreshClock();
}, 10000);
}
EDIT
Based on your comments in rahul's answer...
Update the line:
hour: appendZero(hour),
to
hour: appendZero(((hour + 11) % 12) + 1)
Live Demo
Live Demo
var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function (dt) {
var formatted = '';
if (dt) {
var hours24 = dt.getHours();
var hours = ((hours24 + 11) % 12) + 1;
formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"), hours24 > 11 ? "pm" : "am"].join(" ");
}
return formatted;
}
})();
alert(formatTime(new Date()));