Calculate Time Difference with JavaScript

2019-01-09 07: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.

Format example: 10:00 & 12:30 need to give me: 02:30

Thanks!

回答1:

Here is one possible solution:

function diff(start, end) {
    start = start.split(":");
    end = end.split(":");
    var startDate = new Date(0, 0, 0, start[0], start[1], 0);
    var endDate = new Date(0, 0, 0, end[0], end[1], 0);
    var diff = endDate.getTime() - startDate.getTime();
    var hours = Math.floor(diff / 1000 / 60 / 60);
    diff -= hours * 1000 * 60 * 60;
    var minutes = Math.floor(diff / 1000 / 60);

    // If using time pickers with 24 hours format, add the below line get exact hours
    if (hours < 0)
       hours = hours + 24;

    return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes;
}

DEMO: http://jsfiddle.net/KQQqp/



回答2:

Well this work almost great. Now use this code to calculate: 23:50 - 00:10 And see what you get.Or even 23:30 - 01:30. That's a mess. Because getting the answer the other way in php is:

$date1 = strtotime($_POST['started']);
$date2 = strtotime($_POST['ended']);
$interval = $date2 - $date1;
$playedtime = $interval / 60;

But still, it works like yours. I guess have to bring in the dates aswell?

And again: My hard research and development helped me.

if (isset($_POST['calculate'])) {
$d1 = $_POST['started'];
$d2 = $_POST['ended'];
if ($d2 < $d1) {
    $date22 = date('Y-m-');
    $date222 = date('d')-1;
    $date2 = $date22."".$date222;
} else {
$date2 = date('Y-m-d');
}
$date1 = date('Y-m-d');
$start_time = strtotime($date2.' '.$d1);
$end_time = strtotime($date1.' '.$d2); // or use date('Y-m-d H:i:s') for current time
$playedtime = round(abs($start_time - $end_time) / 60,2);
}

And that's how you calculate time over to the next day. //edit. First i had date1 jnd date2 switched. I need to -1 because this calculation only comes on next day and the first date vas yesterday.

After improving and a lot of brain power with my friend we came up to this:

$begin=mktime(substr($_GET["start"], 0,2),substr($_GET["start"], 2,2),0,1,2,2003);
$end=mktime(substr($_GET["end"], 0,2),substr($_GET["end"], 2,2),0,1,3,2003);
$outcome=($end-$begin)-date("Z");
$minutes=date("i",$outcome)+date("H",$outcome)*60; //Echo minutes only
$hours = date("H:i", $outcome); //Echo time in hours + minutes like 01:10 or something.

So you actually need only 4 lines of code to get your result. You can take only minutes or show full time (like difference is 02:32) 2 hours and 32 minutes. What's most important: Still you can calculate overnight in 24 hour clock aka: Start time 11:50PM to let's say 01:00 AM (in 24 hour clock 23:50 - 01:00) because in 12 hour mode it works anyway.

What's most important: You don't have to format your input. You can use just plain 2300 as 23:00 input. This script will convert text field input to correct format by itself. Last script uses standard html form with method="get" but you can convert it to use POST method as well.



回答3:

Try This

var dif = ( new Date("1970-1-1 " + end-time) - new Date("1970-1-1 " + start-time) ) / 1000 / 60 / 60;


回答4:

This is an updated version of one that was already submitted. It is with the seconds.

function diff(start, end) {
    start = start.split(":");
    end = end.split(":");
    var startDate = new Date(0, 0, 0, start[0], start[1], 0);
    var endDate = new Date(0, 0, 0, end[0], end[1], 0);
    var diff = endDate.getTime() - startDate.getTime();
    var hours = Math.floor(diff / 1000 / 60 / 60);
    diff -= hours * (1000 * 60 * 60);
    var minutes = Math.floor(diff / 1000 / 60);
    diff -= minutes * (1000 * 60);
    var seconds = Math.floor(diff / 1000);

    // If using time pickers with 24 hours format, add the below line get exact hours
    if (hours < 0)
       hours = hours + 24;

    return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes + (seconds<= 9 ? "0" : "") + seconds;
}

My Updated Version:

Allows for you to convert the dates into milliseconds and go off of that instead of splitting.

Example Does -- Years/Months/Weeks/Days/Hours/Minutes/Seconds

Example: https://jsfiddle.net/jff7ncyk/308/



回答5:

With seconds you provided is not get result to me please find my updated function giving you the correct seconds here - By Dinesh J

function diff(start, end) {
    start = start.split(":");
    end = end.split(":");
    var startDate = new Date(0, 0, 0, start[0], start[1],start[2], 0);
    var endDate = new Date(0, 0, 0, end[0], end[1],end[2], 0);
    var diff = endDate.getTime() - startDate.getTime();
    var hours = Math.floor(diff / 1000 / 60 / 60);
    diff -= hours * 1000 * 60 * 60;
    var minutes = Math.floor(diff / 1000 / 60);
    var seconds = Math.floor(diff / 1000)-120;

    // If using time pickers with 24 hours format, add the below line get exact hours
    if (hours < 0)
        hours = hours + 24;

    return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes+ ":" + (seconds <= 9 ? "0" : "") + seconds;
}


回答6:

Depending on what you allow to enter, this one will work. There may be some boundary issues if you want to allow 1am to 1pm

NOTE: This is NOT using a date objects or moment.js

function pad(num) {
  return ("0"+num).slice(-2);
}
function diffTime(start,end) {
  var s = start.split(":"), sMin = +s[1] + s[0]*60,
      e =   end.split(":"), eMin = +e[1] + e[0]*60,
   diff = eMin-sMin;
  if (diff<0) { sMin-=12*60;  diff = eMin-sMin }
  var h = Math.floor(diff / 60),
      m = diff % 60;
  return "" + pad(h) + ":" + pad(m);
}  
document.getElementById('button').onclick=function() {
  document.getElementById('delay').value=diffTime(
      document.getElementById('timeOfCall').value, 
      document.getElementById('timeOfResponse').value
  );
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">



回答7:

   calTimeDifference(){
    this.start = dailyattendance.InTime.split(":");
    this.end = dailyattendance.OutTime.split(":");
    var time1 = ((parseInt(this.start[0]) * 60) + parseInt(this.start[1]))
    var time2 = ((parseInt(this.end[0]) * 60) + parseInt(this.end[1]));
    var time3 = ((time2 - time1) / 60);
    var timeHr = parseInt(""+time3);
    var  timeMin = ((time2 - time1) % 60);
}


回答8:

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(":"));
    }
});


回答9:

We generally need time difference to estimate time taken by I/O operations, SP call etc, the simplest solution for NodeJs (the console is in callback- async execution) is following:

var startTime = new Date().getTime();
//This will give you current time in milliseconds since 1970-01-01

callYourExpectedFunction(param1, param2, function(err, result){
    var endTime = new Date().getTime();
    //This will give you current time in milliseconds since 1970-01-01

    console.log(endTime  - startTime)
    //This will give you time taken in milliseconds by your function

   if(err){
   }
   else{
   }
})