-2

I have been researching about this around Internet but couldn't find a solution. I have this script which displays time in Monday, March 16, 2015, 16:59:40 format which you can see is a 24 hours format and Seconds are not running. The script is

<script type='text/javascript'>
document.getElementById("para1").innerHTML = formatAMPM();

function formatAMPM() {
var d = new Date(),

    seconds = d.getSeconds().toString().length == 1 ? '0'+d.getSeconds() : d.getSeconds(),
    minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
    hours = d.getHours().toString().length == 1 ? '0'+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+':'+seconds+' '
}
</script>

And HTML is

<span id='para1'></span>

You can see the current code running at https://jsfiddle.net/g70rsr1L/ All I want is to convert 24 hours format to 12 hours and a running seconds script within it.

Thanks

Muji
  • 1
  • 1

1 Answers1

0

this from your code, it can help you:

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

function formatAMPM() {
var d = new Date(),

    seconds = d.getSeconds().toString().length == 1 ? '0'+d.getSeconds() : d.getSeconds(),
    minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
    hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
    ampm = d.getHours() >= 12 ? 'pm' : 'am',
            hour = d.getHours() >= 12 ? parseInt(d.getHours()) - 12 : d.getHours(),
    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()+', '+hour+':'+minutes+':'+seconds+' '+ ampm;
}

call this function in setInterval function and keep interval of one second.

Sumit Jha
  • 370
  • 1
  • 5
  • 11