Calculate Time Difference with JavaScript

后端 未结 12 1137
有刺的猬
有刺的猬 2020-12-01 13:20

I have two HTML input boxes, that need to calculate the time difference in JavaScript onBlur (since I need it in real time) and insert the result to new input box.

F

12条回答
  •  青春惊慌失措
    2020-12-01 13:55

    Try this: actually this a problem from codeeval.com

    I solved it in this way .

    This program takes a file as the argument so i used a little node js to read the file.

    Here is my code.

    var fs  = require("fs");
    fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) {
        if (line !== "") {
            var arr = line.split(" ");
            var arr1 = arr[0].split(":");
            var arr2 = arr[1].split(":");
            var time1 = parseInt(arr1[0])*3600 + parseInt(arr1[1])*60 + parseInt(arr1[2]);
            var time2 = parseInt(arr2[0])*3600 + parseInt(arr2[1])*60 + parseInt(arr2[2]);
            var dif = Math.max(time1,time2) - Math.min(time1,time2);
            var ans = [];
            ans[0] = Math.floor(dif/3600);
            if(ans[0]<10){ans[0] = "0"+ans[0]}
            dif = dif%3600;
            ans[1] = Math.floor(dif/60);
            if(ans[1]<10){ans[1] = "0"+ans[1]}
            ans[2] = dif%60;
            if(ans[2]<10){ans[2] = "0"+ans[2]}
            console.log(ans.join(":"));
        }
    });
    

提交回复
热议问题