tags:

views:

329

answers:

4

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.

A: 

jquery doesnt have any date parsing/manipulation built in. I also havent seen many plugins for that. Your best bet would be to create a function that converts the two dates into ints, do the addition, and then turn the result into a date.

Ariel
dates != times.
nickf
A: 

Are you looking for something like Timeago?

DroidIn.net
No, that's not what I'm after but thanks for pointing it out.
Jason
np. it's pretty cute
DroidIn.net
+1  A: 

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.

Danny Roberts
That did the trick, thanks
Jason
A: 

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));
Mark E
I would have gone with `timeInMinutes` and `minutesToString`, only to preference integer operations over floats.
nickf