使用小时,分钟和时间创建计时器倒计时从未来的日期开始的秒数

时间:2012-10-23 04:51:22

标签: javascript

我正在使用我在互联网上找到的某些代码,这些代码会在特定日期创建倒计时。我正在尝试编辑代码,以便它只给我一个从未来日期指定的小时,分​​钟和秒的倒计时。我不能只有从指定时间倒计时的代码,我需要将其倒计时到未来的指定日期。这很重要,因此如果浏览器刷新,倒计时不会重新开始,而是继续停止。我将使用cookie,因此浏览器会记住首次运行时指定的未来日期。

这是HTML:

<form name="count">
<input type="text" size="69" name="count2">
</form>

这是javascript:

window.onload = function()  {
//change the text below to reflect your own,
var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")

function countdown(yr,m,d){
var theyear=yr; var themonth=m; var theday=d
var today=new Date()
var todayy=today.getYear()
if (todayy < 1000)
todayy+=1900;
var todaym=today.getMonth()
var todayd=today.getDate()
var todayh=today.getHours()
var todaymin=today.getMinutes()
var todaysec=today.getSeconds()
var todaystring=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec

futurestring=montharray[m-1]+" "+d+", "+yr

var dd=Date.parse(futurestring)-Date.parse(todaystring)
var dday=Math.floor(dd/(60*60*1000*24)*1)
var dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1)
var dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1)
var dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1)
if(dday==0&&dhour==0&&dmin==0&&dsec==1){
document.forms.count.count2.value=current
return
}
else
document.forms.count.count2.value= dhour+":"+dmin+":"+dsec;
setTimeout(function() {countdown(theyear,themonth,theday)},1000)
}
//enter the count down date using the format year/month/day
countdown(2012,12,25)
}

我确信上面有多余的代码,因为我只需要一小时,分钟和秒,我想传递给countdown()函数。年,月和日是不重要的,但正如我所说,这是我试图编辑的代码,我在互联网上找到了。任何帮助将非常感激。谢谢!

3 个答案:

答案 0 :(得分:4)

您可以为目标时间创建日期对象,并获得与当前日期对象的差异。请注意,这取决于客户端是否具有正确设置的时钟。

function timeDiff(target) {

  function z(n) {return (n<10? '0' : '') + n;}

  var timeDiff = target - (new Date());
  var hours    = timeDiff / 3.6e6 | 0;
  var minutes  = timeDiff % 3.6e6 / 6e4 | 0;
  var seconds  = timeDiff % 6e4 / 1e3 | 0;

  return z(hours) + ':' + z(minutes) + ':' + z(seconds);
}

alert(timeDiff(new Date(2012,9,23,17,50,0)));

在下一整秒后的几毫秒内每秒运行一次。我会留给你的。

修改

到底是什么,这是一个叫它的计时器。只需要在文档中使用id为“timer”的元素:

function doCountDown(target) {
  document.getElementById('timer').innerHTML = timeDiff(target);
  var lag = 1020 - (new Date() % 100);
  setTimeout(function(){doCountDown(target);}, lag);
}

window.onload = function() {
  doCountDown(new Date(2012,9,23,17,50,0));
}

答案 1 :(得分:3)

您可以使用jquery countdown timer集成很简单,并且有多种选项可以以不同的格式显示....

答案 2 :(得分:2)

怎么样

now = new Date();
then = new Date("30 Oct 2013");
time_diff_in_milliseconds = then-now;

integer_seconds=(time_diff_in_milliseconds/1000) >>0;
minutes = seconds / 60 |0;  // another convention to get floor
... etc.

您也可以将时间也放在字符串中。

a=new Date('Oct 30 2013 07:55:07'); b=new Date('Feb 28 2000 20:12:33');

a-b
..
431350954000