-1

I want to calculate duration using start time and end time.

I have a code that gets me the hours, but I need both hours and minutes also.

What changes should I make to the code?

function timeDiff( first, second ) {
    var f = first.split(' '), s = second.split(' ');

    if( first == '12 AM' ) f[0] = '0';
    if( first == '12 PM' ) f[1] = 'AM';
    if( second == '12 AM' ) s[0] = '24';
    if( second == '12 PM' ) s[1] = 'AM';

    f[0] = parseInt( f[0], 10 ) + (f[1] == 'PM' ? 12 : 0);
    s[0] = parseInt( s[0], 10 ) + (s[1] == 'PM' ? 12 : 0);

    return s[0] - f[0];
}


var FirstTime = '1 AM';
var SecondTime = '12 pM';

alert( timeDiff( FirstTime, SecondTime ) );​
Paul T. Rawkeen
  • 3,994
  • 3
  • 35
  • 51
Midhun
  • 27
  • 1
  • 3
  • 10
  • http://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript – TJ- Dec 28 '12 at 09:35
  • This is for date also right.i just need the duration of time. and i use a time picker to get the time – Midhun Dec 28 '12 at 09:38
  • Other pointers http://stackoverflow.com/questions/1787939/check-time-difference-in-javascript and/or http://blogs.digitss.com/javascript/calculate-datetime-difference-simple-javascript-code-snippet/ – acostache Dec 28 '12 at 09:39

3 Answers3

1
var time1 = {hour: 12, minute: 30, second: 15};
var time2 = {hour: 13, minute: 40, second: 25};

var d1 = new Date(2000, 01, 01, time1.hour, time1.minute, time1.second);

var d2 = new Date(2000, 01, 01, time2.hour, time2.minute, time2.second);

var diff = Math.abs( ( d1.getTime() - d2.getTime() ) / 1000 ); // difference in seconds

var hours = Math.floor(diff / 3600); // number of full hours
var minutes = Math.floor(diff / 60); // number of full minutes
var seconds = diff - minutes * 60; // remaining seconds

// remaining seconds also can be obtained like this
var seconds = diff % 60;
Paul T. Rawkeen
  • 3,994
  • 3
  • 35
  • 51
0

Please consider using Moment.js as it will make your life easier on this.

Boris Brdarić
  • 4,674
  • 2
  • 24
  • 19
0

See this : http://jsfiddle.net/R8URw/

function timeDiff(first, second) {
if (first === '' || second === '') {
    return false;
}
var f = first.split(' '),
    s = second.split(' ');

if (first == '12:00 AM') {
    f[0] = '0';
}
if (first == '12:00 PM') {
    f[1] = 'AM';
}
if (second == '12:00 AM') {
    s[0] = '24';
}
if (second == '12:00 PM') {
    s[1] = 'AM';
}


var time1 = f[0].split(':'),
    time2 = s[0].split(':');

time1 = time1[0] * 3600 + time1[1] * 60;
time2 = time2[0] * 3600 + time2[1] * 60;
var td = time2 - time1,
    hours = parseInt((td / 3600), 10),
    minutes = parseInt(((td - hours * 3600) / 60), 10),
    diff = ((hours < 10 && hours >= 0) ? ('0' + hours) : hours) + ':' + ((minutes < 10 && minutes >= 0) ? ('0' + minutes) : minutes);
return (diff);
}

And:

var FirstTime = '1:00 AM';
var SecondTime = '12:09 pM';

alert(timeDiff(FirstTime, SecondTime));​
Anujith
  • 9,370
  • 6
  • 33
  • 48