告诉两个给定时间值之间的秒数

时间:2018-03-03 08:19:20

标签: javascript html time

我想在我的html中有两个<input type="text">,一个用于起点,一个用于终点。然后你就可以写两次了

ex:[8:15] - [14:30]提醒(“XXXXX秒”)

我想知道8:15到14:30之间有多少秒。两次都是在同一天。并且只是为了让事情变得更简单(至少对我而言)我想要提醒结果。

这将稍后用于进度条,它将具有开始和结束

function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
    h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
var s = today.getSeconds();
var sh = document.getElementById('starth').value;
var sm = document.getElementById('startm').value;
var spcode = sh / sm + 1;
var timecode = s + h / m;
if (timecode == spcode) {
    setTimeout(move, 200)
}
}
tion checkTime(i) {
if (i < 10) {
    i = "0" + i
}; // add zero in front of numbers < 10
return i;
}


//Menu
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}

function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}

//progress bar

function move() {
var elem = document.getElementById("myBar");
var nof = document.getElementById('sec').value;
var width = 0;
var id = setInterval(frame, +nof); //1 frame > 4 = 1sec
function frame() {
    if (width >= 999.0) {
        clearInterval(id);
    } else {
        width++;
        elem.style.width = width * 0.1 + '%';
        elem.innerHTML = (width + 1) / 10 + '%';

    }
}
}

1 个答案:

答案 0 :(得分:1)

var year = '2018';
var month = '04';
var day = '18';

function diff() {
   var start_time=document.getElementById("start_time").value;
   var end_time=document.getElementById("end_time").value;
   var start_date=new Date(year,month,day,start_time.split(':')[0],start_time.split(':')[1]);
   var end_date=new Date(year,month,day,end_time.split(':')[0],end_time.split(':')[1]);
   var difference=(end_date-start_date)/1000;
   console.log(difference);
   document.getElementById("difference").innerHTML="Differnce is "+difference+" seconds";
}
<input type="text" id="start_time" placeholder="4:15">
<input type="text" id="end_time" placeholder="4:16">
<input type="submit" onclick="diff()">
<p id="difference"></p>

说明: -

我从输入字段读取了两个值。然后将这两个值转换为Date对象。这里split会拆分字符串并给出数组,所以它会给我几小时和几分钟,用于将字符串转换为Date。然后我从end_date中减去start_date,它会给我milliseacond的结果,并将它除以1000我将这个差异转换为秒。