0

http://jsfiddle.net/2Tcvc/

document.getElementById("para1").innerHTML = formatAMPM();

function formatAMPM() {
    var d = new Date(),
        minutes = d.getMinutes().toString().length == 1 ? '0' + d.getMinutes() :         d.getMinutes(),
        hours = d.getHours().toString().length == 1 ? '' + d.getHours() : d.getHours(), 
        ampm = d.getHours() >= 12 ? 'pm' : 'am',
        months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',     'August', 'September', 'October', 'November', 'December'],
        days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    return days[d.getDay()] + ', ' + months[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear() + ' ' + hours + ':' + minutes + ampm;
}

I'm not very good with js and everytime I try something it breaks. Can anyone show me how to show a 12hr format and possibly explain what's happening? Thanks in advance.

1 Answers1

0

You need to subtract 12 from the hours if it's PM, and change 0 to 12am.

hours = d.getHours();
ampm = hours >= 12 ? 'pm' : 'am';
if (hours == 0) {
    hours = 12; // midnight is 12am
} else if (hours > 12) {
    hours -= 12;
}
if (hours.toString().length == 1) {
    hours = '0' + hours;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612