在html输入字段

时间:2017-05-27 17:51:57

标签: javascript

我已经尝试了很长时间,但我失败了,请帮忙,

var set_time = document.getElementById('set');
set_time.onclick = function start_time() {
    var myDate = new Date();

然后制作自定义时间

var h = myDate.getHours();
    var m = myDate.getUTCMinutes();
    var s = myDate.getSeconds();
    var time = h + ':' + m + ':' + s;

之后在输入字段中设置时间

document.getElementById('start').value = time;
};

与上述设定结束时间相同

var end_time = document.getElementById('end');
end_time.onclick = function end_time() {
    var myDate = new Date();

将结束时间存储为输入字段

var time = h + ':' + m + ':' + s;
    document.getElementById('stop').value = time;
};

现在我想找到差异或持续时间并在输入字段中设置"持续时间"

function duration(){
  var start= document.getElementById('start').value;
  var stop = document.getElementById('stop').value;

  // i want to calculate duration and  display the duration in an input field

  document.getElementById('duration').value = result;

};
setInterval(duration, 1000);

1 个答案:

答案 0 :(得分:0)

我想它可以写得更好,但为了便于阅读:enter image description here

  var start= document.getElementById('start').value;
  var stop = document.getElementById('stop').value;

  var startVal = document.getElementById('start').value.split(':');
  var stopVal = document.getElementById('stop').value.split(':');
  var h = (parseInt(stopVal[0])-parseInt(startVal[0]))*3600;
  var m = (parseInt(stopVal[1])-parseInt(startVal[1]))*60;
  var s = (parseInt(stopVal[2])-parseInt(startVal[2]))
  var dur = h+m+s;

  var hOut = Math.floor(dur/3600)
  var mOut = Math.floor((dur-hOut*3600)/60)
  var sOut = dur-hOut*3600-mOut*60
  var result = hOut+':'+mOut+':'+sOut
  if (!isNaN(sOut)) document.getElementById('duration').value = result;

编辑:另一个版本,使用日期:

  var start= document.getElementById('start').value;
  var stop = document.getElementById('stop').value;
  if (!start || !stop) return;

  var startVal = new Date(zeroDay+start+timeZone)
  var stopVal = new Date(zeroDay+stop+timeZone)

  var dur = stopVal-startVal

  var result = new Date(dur-60*60*1000)
  document.getElementById('duration').value = result.toTimeString().split(' ')[0];

在哪里'零日'是历史上的第一天(日期) - 1970年1月1日。 PEN