Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing time subtraction with jQuery

Tags:

jquery

I have two time values on a page:

8:00
22:30

I need to subtract 8 from 22:30 and get 14:30.

Is there a straight forward way to do that in jQuery? Plug-ins are fine by me if they're necessary.

Update: The second number is a grand total so it could also be something like

48:45

Anything I subtract from it should just subtract the value from it as a total, not do any date related calculations.

like image 435
Jason Avatar asked Jan 12 '10 22:01

Jason


3 Answers

You can do it in javascript.

Suppose you have start = '8:00' and end = '22:30'. The code is as follows:

<script type="text/javascript">
    var start = '8:00';
    var end = '23:30';

    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;
    diff = hour + ":" + min;

    alert(diff);
</script>

In the end, diff is your time difference.

like image 187
Danny Roberts Avatar answered Sep 24 '22 11:09

Danny Roberts


i think try this code -:

 var start = '8:00';
 var end = '23:30';

var startDate = new Date("1/1/1900 " + start _time);
var endDate = new Date("1/1/1900 " + end );
var difftime=endDate - startDate; //diff in milliseconds
like image 45
hari maliya Avatar answered Sep 22 '22 11:09

hari maliya


jQuery isn't required, you can do it in straight JavaScript with something simple like:

function timeInHours(str)
{
   var sp = str.split(":");
   return sp[0] + sp[1]/60;
}

function hoursToString(h)
{
   var hours = floor(h);
   var minutes = (h - hours)*60;

   return hours + ":" + minutes;
}

var time1 = "08:00";
var time2 = "22:30";

var tot = hoursToString(timeInHours(time2) - timeInHours(time1));
like image 39
Mark Elliot Avatar answered Sep 22 '22 11:09

Mark Elliot