0

Like many before me I am tryin gto calculate the difference between two times ( Start and end time for a job)

I've created the code below but for some reason am getting a weird answer. I suspect it is to do with creating a Date object with no date in it.

Any pointers would be very educational as to why I'm getting a dud answer.

my code:

// Add in a rightStr() function so we can pad single number answers to two digit answers 
function rightStr( myString, numChars){
        return myString.slice( numChars * -1 );

    }

// Input is 12:00 AM and 2:15 AM    from jquery date pickers
function get_time_diff( starttime, endtime )
{

    var starttime = typeof starttime !== 'undefined' ? starttime : "2014-01-01 00:00:00";
    var endtime = typeof endtime !== 'undefined' ? endtime : "2014-01-01 00:00:00";

    var starttime = new Date( "01/01/2000 " + starttime ).getTime();
    var endtime = new Date( "01/01/2000 " + endtime ).getTime();

// Values show as 946638000000 - start
//                946646100000   - end 

    if( isNaN(starttime) )
    {
        return "";
    }

    if( isNaN(endtime) )
    {
        return "";
    }


    if (starttime <= endtime) {
        var milisec_diff = endtime - starttime;
    }else{
        var milisec_diff = 0;   // We don't allow negative returns
    }

 // milisec_diff  is 8100000
 // Which is 2.25 if it is divided by 60  * 60 * 1000   ( secs, mins, millisecs)
// this is a correct answer so far. 

    var date_diff = new Date( milisec_diff );
// date_diff =  Thu Jan 01 1970 15:15:00 GMT+1300 (New Zealand Standard Time)
// this is where it goes wrong. 

    var hh = rightStr("0" + date_diff.getHours().toString(), 2) ;
    var mm = rightStr("0" + date_diff.getMinutes().toString(), 2) ;
    return  hh + ":" + mm + ":00"

     // returns 15:15 
}
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
Shane
  • 71
  • 4

4 Answers4

1

Simply you can try this: 1st Function date difference and 2nd function time.

//Function Date difference
function dateDiffer(startdate, enddate){
 var start = new Date(startdate);
 var end = new Date(enddate);
 var timeDiff = Math.abs(end.getTime() - start.getTime());
 var Daydiff = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
 return Daydiff;
}


//Function time difference
function dateTimeDiffer(startDTime, endDtime){
 var startTime = new Date(startDTime);
 var endTime = new Date(endDtime);
 var diff = endTime.getTime() - startTime.getTime();
 var msec = diff;
 var hh = Math.floor(msec / 1000 / 60 / 60);
 msec -= hh * 1000 * 60 * 60;
 var mm = Math.floor(msec / 1000 / 60);
 msec -= mm * 1000 * 60;
 var ss = Math.floor(msec / 1000);
 msec -= ss * 1000;
 return hh + ":" + mm + ":" + ss;
}

//call date differece
alert("Date: "+dateDiffer("7/13/2016", "12/15/2016"));

//call date time differ
alert("DateTme: "+dateTimeDiffer("08/05/2016 23:41:20", "08/06/2016 02:56:32"));
AHJeebon
  • 1,218
  • 1
  • 12
  • 17
  • Parsing strings with the Date constructor (or Date.parse) is not recommended as it's largely implementation dependent and likely to result in incorrect dates or different results in different implementations. Manually parse strings with a custom function or library. – RobG Oct 16 '16 at 20:58
0

Once you convert your inputs to Date objects, you can the following:

var time1 = "12:00 AM";
var time2 = "2:15 AM";


function timeToDate(time){

    var hour = 0;
    var second = 0;

    if (time){
        var split1 = time.split(' ');

        var split2 = split1[0].split(':');

        hour = parseInt(split2[0]);
        second = parseInt(split2[1]);

        if (split1[1] == 'PM'){
            hour += 12;
        }
    }

    return Date.UTC(2000,1,1,hour,second);
}


var date1 = timeToDate(time1);
var date2 = timeToDate(time2);

var diffInMilliseconds = date2 - date1;

console.log(diffInMilliseconds);

online demo - https://repl.it/DxW1/0

Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
0

you can use moment.js lib to handle everything about datetime

/** padding zero function */
function pad(n) {
  const width = 2
  const z = '0'
  n = n + ''
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n
}

/** get diff date */
function getDiffDate(d1, d2) {
  /** get duration between 2 datetime */
  const duration = moment.duration(d2.diff(d1))
  
  /** get each result */
  const YY = pad(duration._data.years)
  const MM = pad(duration._data.months)
  const DD = pad(duration._data.days)
  const hh = pad(duration._data.hours)
  const mm = pad(duration._data.minutes)
  const ss = pad(duration._data.seconds)
  
  /** print result ,e.g., 00-00-00 01:03:00 */
  console.log(`${YY}-${MM}-${DD} ${hh}:${mm}:${ss}`)
}

/** define 2 datetime here */
const d1 = moment('2016-01-29 10:01:00')
const d2 = moment('2016-01-29 11:04:00')

getDiffDate(d1, d2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
Alongkorn
  • 3,968
  • 1
  • 24
  • 41
0

Never parse strings with the Date constructor (or Datep.parse, they are equivalent for parsing).

When you do:

// Input is 12:00 AM and 2:15 AM    from jquery date pickers
function get_time_diff( starttime, endtime ) {
  var starttime = typeof starttime !== 'undefined' ? starttime : "2014-01-01 00:00:00";

you are setting starttime to a string, so later when you do:

var endtime = typeof endtime !== 'undefined' ? endtime : "2014-01-01 00:00:00";

var starttime = new Date( "01/01/2000 " + starttime ).getTime();

you are creating a string like "01/01/2000 12:00 AM". Parsing that with Date is entirely implementation dependent and could result in the expected outcome or something else, including an invalid date.

Always parse strings with a custom function or use a library.

Once you correctly parse the strings, you can get the difference in milliseconds by subtracting one date from the other.

If all you want to do is get differences between times, then don't create Date objects at all. Convert the times to some common unit (maybe seconds), get the difference and convert back to HH:mm or whatever.

A function to convert a time to seconds can be as follows (the input should be tested first to ensure it's within acceptable bounds):

/* Convert time like 2:15:00 AM to seconds
** @param {string} s - string to pase in h:mm:ss format
** @returns {number} time converted to seconds
*/
function toSecs(s) {
  var b = s.match(/\d+/g) || [];
  return (b[0]%12||0)*3600 + (b[1]||0)*60 + (+b[2]||0) + (/pm$/i.test(s)? 12*3600 : 0);
}

console.log(toSecs('12:01 am'));
console.log(toSecs('12:01:01 am'));
console.log(toSecs('12:01 pm'));
RobG
  • 142,382
  • 31
  • 172
  • 209