0

Possible Duplicate:
check time difference in javascript
calculate time difference in javascript

this is my block of code to pull times from a form input,

start = group.find('.startTime').val().replace(':',''),     // like 0100
end = group.find('.endTime').val().replace(':',''),         // like 0300
timeDiff = (end - start) < 0 ? (end - start + 2400) : (end - start),

timeDiff accounts for times passing midnight, so like if I try and subtract 2300 from 0100, and get -2200, it adds the 2400 to get the correct difference of 0200, or 2 hours.

my problem arises where i try to subtract some times like 2100 - 2030 (which should give me a half hour) but because its just a raw number i get the actual difference of 70. my question is how would I correctly subtract these? If i need to convert it to a date or time object what would be the proper way of doing so? I looked into the setTime method but that didn't sound like what i needed.

Thanks in advance.

Community
  • 1
  • 1
Adam Bickford
  • 187
  • 1
  • 2
  • 13
  • Strange you were not told the many other questions when you authored this question... It is a FAQ – mplungjan Jan 20 '13 at 16:37
  • Have a look at `setHours`/`setMinutes` if you want to use `Date` objects – Bergi Jan 20 '13 at 17:14
  • the approach in [check time difference in javascript](http://stackoverflow.com/questions/1787939/check-time-difference-in-javascript) was what i needed. just wasn't searching for the right terms. – Adam Bickford Jan 20 '13 at 17:35

1 Answers1

0

Without Date objects (which seems OK for time-only values), you should convert the time to minutes or hours - always calculate with only one unit (and especially never mix them into one decimal number representing a sexagesimal one)!

function toTime(string) {
    var m = string.match(/(\d{2}):({\d2})/);
    return m && 60 * parseInt(m[1], 10) + parseInt(m[2], 10),
}
var start = toTime( group.find('.startTime').val() ),
    end = toTime( group.find('.endTime').val() );

var timeDiff = Math.abs(end - start);

function fromTime(minutes) {
    var m = minutes % 60,
        h = (minutes - m) / 60;
    return ("0"+h).substr(-2)+":"+("0"+m).substr(-2);
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • thanks, i'll remember that, i ended up setting the date object like the answer in this [question](http://stackoverflow.com/questions/1787939/check-time-difference-in-javascript), then subtracting the millisecond values and converting them to hours. – Adam Bickford Jan 20 '13 at 17:29