javascript实用程序,递增/递减到下一个15分钟的间隔

时间:2010-10-15 19:01:25

标签: javascript date time

有人可以在这里发现任何错误或性能改进吗?

<a href='#' id='from_arrow_down' onclick="timeOffset(-1,'from_time');">Click me</a>

function timeOffset(offset,time_id)
{

  // javascipt utility that increments/decrements to the next 15 minute interval.
  // When user pushes a button, program will get time from input box, 
  // increment (offset=1) or decrement (offset=-1) to next (or previous)
  // quarter hour and out value back to input box.

  // This is used on handheld devices where keyboard is very small and input is     
  // difficult and time consuming.

  var pass_time = document.getElementById(time_id).value;
  var tempDate;

  // break in to hours and minutes 
  var HH = pass_time.substr(0,2);
  var MM = pass_time.substr(2,4);
  // dummy date
  try{
  tempDate = new Date("2000", "01", "01", HH, MM, "00", "0000");
  }
  catch(err)
  {
   alert("invalid time (HHMM)");
   return;
  }

  // dummy minutes
  var minutes = 999;

  // iterate until we have reached an inter
  while (minutes != 0 && minutes != 15 &&  minutes != 30 && minutes != 45){
   tempDate.setMinutes( tempDate.getMinutes() + offset );
   minutes = tempDate.getMinutes();   
   document.getElementById(time_id).value = cleanUp(tempDate.getHours()) + "" + cleanUp(tempDate.getMinutes());
  }

}

function cleanUp(d)
{
  if (d < 10){
   d = "0" + d;
  }
  return d;
}

2 个答案:

答案 0 :(得分:1)

while循环对此非常有用。我会使用setTimeout - 如果需要,或者每需要一个X增量,每秒调用一次。

答案 1 :(得分:0)

是的,您可以计算到下一个间隔的距离,然后在该值上运行while循环的内容。您无需使用“分钟”的临时值来不断修改页面内容。

E.G。,将分钟投射到浮点数,除以15,使用floor / ceil函数进行递减/递增,然后再次乘以15。这只是我的头脑,它可能不适用于角落案件等。