display time am/pm inside a div with javascript

2019-09-02 14:30发布

Hi Everyone I am sorry if this question has been answered before but I haven't been able to find a solution. I am completely new to js so please be nice :)

I wanted to ask how can I have the time display inside a div? I can't get this function to display on my page. When I launch the page in the browser, it is just blank.

Thank you, I hope my question makes sense.

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

function formatAMPM(date) {
  var elem = document.getElementById("para1");
  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;
 }

3条回答
Juvenile、少年°
2楼-- · 2019-09-02 14:49
document.getElementById("para1").innerHTML = formatAMPM();

function formatAMPM() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours || 12;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}

DEMO VIEW

查看更多
Rolldiameter
3楼-- · 2019-09-02 14:50

You need this:

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

And you might also want to wrap it in something like jQuery's ready() to make sure the DOM has been loaded:

$(document).ready(function() {
    // Handler for .ready() called.
});

http://api.jquery.com/ready/

jQuery's isn't the only way, but just a suggestion.

查看更多
唯我独甜
4楼-- · 2019-09-02 14:50

You can return it in a user-familiar time string with toLocaleTimeString().

A replace will remove the seconds counter-

function formatAMPM() {
  var d=new Date().toLocaleTimeString();
  return d.replace(/^(\d{2}:\d{2}):\d{2}(.*)/, '$1$2');
}

Or you can call this or your method on a timer-

onload= function(){
    window.showTimer= setInterval(function(){
        var date= new Date(),
        hours= date.getHours(),
        time= date.getMinutes();
        if(time<10) time= '0'+time;
        document.getElementById("para1").innerHTML=
        (hours%12 || 12)+':'+time+(hours>= 12? ' pm':' am');
    },1000);
}
查看更多
登录 后发表回答