jQuery javascript时钟可设置的时间

jQuery javascript clock with settable time?

本文关键字:时间 设置 javascript 时钟 jQuery      更新时间:2023-09-26

我正在寻找一个简单的jQuery时钟。

有吨在那里,但我正在寻找一个,我可以设置当前时间,和输出格式。

所以我希望能够调用像

这样的东西
$('#clock').clock({
  format: 'l dS F Y, h:i a',    //PHP date format, but anything that can mimic this output is good
  date:   '2012-07-01 23:59:59' //MYSQL date format, but can output as anything
});

是否有这样的东西(即使是原始的js也会这样做)。

为时钟创建计数器非常简单,您可能可以用更少的时间来编写一个计数器,而不是在这里查看您将得到的答案。下面是我做的一个原型继承的例子。

只是格式化输出,但你喜欢,添加CSS你的心内容,使其看起来不错。

// Create a digital clock
// Write time in hh:mm:ss.nnn format
// el is an element
function Clock(el) {
  if (typeof el == 'string') el = document.getElementById(el);
  this.el = el;
}
// Clock methods
Clock.prototype = {
  // Utilty functions
  addZ: function(n) {
    return n < 10? '0' + n : '' + n;
  },
  addZZ: function(n) {
    return n < 10? '00' + n : n < 100? '0' + n : '' + n;
  },
  formatTime: function(d) {
    return  this.addZ(d.getHours()) + 
      ':' + this.addZ(d.getMinutes()) +
      ':' + this.addZ(d.getSeconds()) + 
      // Milliseconds are just for debug, remove from finished version
      '.' + this.addZZ(d.getMilliseconds())
  },
  update: function() {
    var clock = this;
    var d = new Date();
    // Set next run to just after full second
    var interval = 1020 - d.getMilliseconds()
    this.el.innerHTML = this.formatTime(d);
    setTimeout(function(){
      clock.update();
    }
    ,interval);
  }
};
// Create a new clock
// el is id or element to display text in
function newClock(el) {
  var y = new Clock(el);
  y.update();
}

编辑

通用日期格式函数:http://blog.stevenlevithan.com/archives/date-time-format

将日期格式化为Tuesday 05th July 2011, 10:31 am:

var formatDate = (function() {
  // Days of the week, zero is Sunday
  var days = ['Sunday','Monday','Tuesday','Wednesday',
              'Thursday','Friday','Saturday'];
  // Months of the year, zero is January
  var months = ['January','February','March','April',
                'May','June','July','August','September',
                'October','November','December'];
  // Format single digit numbers
  function addZ(n) {
    return n<10? '0' + n : '' + n;
  }
  // Add ordinal to numbers
  function addOrdinal(n) {
    return ['th','st','nd','rd'][(''+n).slice(-1)] || 'th';
  }
  return function (date) {
    var d = addZ(date.getDate());
    var h = date.getHours();
    var ap = h < 12? 'am' : 'pm';
        h = addZ(h > 12? h - 12 : h);
    return days[date.getDay()] + ' '
      + d + addOrdinal(d)  + ' '
      + months[date.getMonth()] + ' '
      + date.getFullYear() + ', '
      + h + ':'
      + addZ(date.getMinutes()) + ' '
      + ap
  }
}());