使用 jquery 的两个日期时间之间的倒计时

Countdown of between two datetime using jquery

本文关键字:日期 时间 之间 两个 倒计时 jquery 使用      更新时间:2023-09-26

>我有两个日期,一个是2016-02-23 15:12:12,另一个是2016-02-29 18:16:42,然后如何显示hh:mm:ss倒计时以使用jquery减去这两个日期请帮忙提前谢谢

你试试这样

var timer;
var compareDate = new Date();
compareDate.setDate(compareDate.getDate() + 7); //just for this demo today + 7 days
timer = setInterval(function() {
  timeBetweenDates(compareDate);
}, 1000);
function timeBetweenDates(toDate) {
  var dateEntered = toDate;
  var now = new Date();
  var difference = dateEntered.getTime() - now.getTime();
  if (difference <= 0) {
    // Timer done
    clearInterval(timer);
  } else {
    var seconds = Math.floor(difference / 1000);
    var minutes = Math.floor(seconds / 60);
    var hours = Math.floor(minutes / 60);
    var days = Math.floor(hours / 24);
    hours %= 24;
    minutes %= 60;
    seconds %= 60;
    $("#days").text(days);
    $("#hours").text(hours);
    $("#minutes").text(minutes);
    $("#seconds").text(seconds);
  }
}

您可以使用countDownjs

http://countdownjs.org/demo.html

注意:最好使用第三方库,因为有人为此编写了代码,您最好插入它并开始使用 当您有一些资源时不要浪费时间。

这里有两个问题要解决。

  1. 你如何获得JavaScript中两个Date对象之间的区别
  2. 您如何以小时、分钟、秒为单位显示这种差异

获取 JavaScript 中两个Date对象之间的差异

首先,您需要获取每个Date对象的 Unix 时间戳,即从纪元开始经过的总秒数。然后,您可以减去这两个值以获得以秒为单位的总差。为此,我们依靠DategetTime()方法,该方法在javascript中返回自纪元以来的毫秒数。

var start = new Date('2016-02-12 15:12:12');
var end   = new Date('2016-02-22 18:16:42');
/* This gives us an integer value of the difference in seconds */
var diff  = Math.round((end.getTime() - start.getTime()) / 1000);

以小时、分钟和秒为单位显示差异

第二部分需要执行一些基本的时钟算术,以从diff值中获取小时数、分钟数和秒数。

由于一小时中有 3600 秒,因此此值中的总小时数为 Math.floor(diff / 3600) 。由于每分钟有 60 秒,因此此值中的总分钟数为 Math.floor((diff - (hours * 3600)) / 60) ,其中 diff 等于小时数乘以 3600 。随后,这个值中的总秒数只是diff的余数,减去小时和分钟,从商 60 ((diff - hours * 3600) - (minutes * 60) % 60),我们从模运算符得到

function getClock(seconds) {
    var hours = Math.floor(diff / 3600);
    diff -= hours * 3600
    var minutes = Math.floor(diff / 60);
    diff -= minutes * 60;
    var seconds = diff % 60;
    return hours + ":" + minutes + ":" + seconds;
}

将一切整合在一起

如果你想显示这样的倒计时时钟,有一些漂亮的jquery插件jQuery倒计时,它使这个过程变得容易得多。但我觉得解释编程背后的细节很重要,无论如何。

var date1="2016-02-12 15:12:12";
var date2="2016-02-22 18:16:42";
var d1= date1.split(" ");
d1=d1[1];
var d2= date2.split(" ");
d2=d2[1];
d1=d1.split(":");
d2=d2.split(":");
var hours=d2[0]-d1[0];
var mins=d2[1]-d1[1];
var sec=d2[2]-d1[2];
var countdown=hours+":"+mins+":"+sec;
console.log(countdown);

这将为您提供剩余时间。有一些用于时间倒计时的库。您可以使用它们