如何让我的JavaScript时钟显示AM / PM?

时间:2014-09-12 00:06:31

标签: javascript

我希望我的时钟根据时间显示是上午还是下午。以下是我到目前为止的情况:

HTML

<div id='andro-clock'><div id='date'></div><div id='time'></div></div>

JS

$.fn.androClock = function() {
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    function getTime() {
      var date = new Date(),
          hour = date.getHours(hour >= 12) ? "PM" " : "AM");
      return {
        day: days[date.getDay()],
        date: date.getDate(),
        month: months[date.getMonth()],
        hour: appendZero(((hour + 11) % 12) + 1),
        minute: appendZero(date.getMinutes()),
        year: appendZero(date.getFullYear())
      };
    }
    function appendZero(num) {
      return (num >= 0 && num < 10) ? "0" + num : num + "";
    }

    function refreshClock() {
      var now = getTime();
      $('#date').html('Today is' + "&nbsp" + now.day + ',' + "<br>" + now.month + "&nbsp" + now.date + ',' + "&nbsp" + now.year);
      $('#time').html(now.hour + ":" + now.minute);
      setTimeout(function() {
        refreshClock();
      }, 10000);
    }
    refreshClock();
};

$('#andro-clock').androClock();

正如我之前提到的,我希望这个时钟能够显示上午或下午,并且还可以在单​​个数字时间之前消除不必要的0,具体取决于时间。它是12小时格式,目前只显示时间,例如07:49,我希望早上7:49或下午。任何帮助表示赞赏。谢谢!

0 个答案:

没有答案