7

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.

2
  • do you need to be able to overnight? Commented Jan 12, 2010 at 22:56
  • No overnight...the second value is always a grand total of hours.
    – Jason
    Commented Jan 12, 2010 at 22:57

5 Answers 5

10

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.

1
  • Thanks for solution, but would you test start: 6:00 and end: 1:30 ? it returns -5 in hour...
    – Web Design
    Commented May 2, 2022 at 10:05
2

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
1

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));
1
  • I would have gone with timeInMinutes and minutesToString, only to preference integer operations over floats.
    – nickf
    Commented Jan 12, 2010 at 23:17
0

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.

0
0

Are you looking for something like Timeago?

1
  • No, that's not what I'm after but thanks for pointing it out.
    – Jason
    Commented Jan 12, 2010 at 23:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.