Studio DnB Studio DnB - 27 days ago 5
Javascript Question

Javascript time calculating from yesterday to tomorrow

So let me explain. I'm working on a site where people keep log on how long they were doing something. The problem is when someone is doing something from let's say 23:00 to 2:00. The script I have now says it's -21hours.

The second problem is it calculates minutes in decimals. For example 1:15 is 1,25. This isn't really a big problem but my secondary question is can I get results in minutes?

For my primary question, how can I set a condition if from one day to another calculate 24-$result else calculate normally?

This is what I have now:

$(function() {
$("#check").click(function() {
var start = $(".preveri_ure").val();
var end = $(".preveri_ure_2").val();
s = start.split(':');
e = end.split(':');
min = e[1]-s[1];
hour_carry = 0;
if(min < 0){
min += 60;
hour_carry += 1;
}
hour = e[0]-s[0]-hour_carry;
min = ((min/60)*100).toString()
diff = hour + "," + min.substring(0,2);
$("#show").text("Task lasted for : " + diff + "hours");
});


EDIT:

Start and End hours are inputted by users in an input field with this format:
Start: 7:00
End 20:15

Also time difference is always less than 24 hours. So date isn't required.

Answer

Completely agree with @Scott Marcus. it's easier for comparison if there is full date instead of just hour and Minute.

But from @Studio DnB perspective, let's consider Start and End time belong to same day. but, start time must be smaller than end time in drop-down selection.

here is code

var tempStartDate = new Date(); // just inintialise start and end date
var tempEndtDate = new Date();      
s = date1.split(':');
e = date2.split(':');
tempStartDate.setHours(s[0], s[1], 0); // set Hours and Minutes for start and end date
tempEndtDate.setHours(e[0], e[1], 0);

var startTime ;
var endTime ;
  // compare to make start time less then end time always for same day log
if (tempEndtDate.getTime() > tempStartDate.getTime()){
      endTime = tempEndtDate.getTime();
      startTime= tempStartDate.getTime();
  }
else {
      endTime = tempStartDate.getTime();
     startTime= tempEndtDate.getTime();
 }

  var difference = endTime - startTime;

  var hoursDifference = Math.floor(difference/1000/60/60);
    difference -= hoursDifference*1000*60*60

    var minutesDifference = Math.floor(difference/1000/60);
    difference -= minutesDifference*1000*60

Example is on https://jsfiddle.net/fNPvf/32377/

Comments