0

I'm trying to subtract two times from each other and for the most part works but in some scenarios it's giving the wrong output.

Here's my code so far:

  //postDateTime looks like 2015-04-23T22:23:32.902Z

  //Split the date and time
  var postDateTime2 = postDateTime.split("T");

  //remove the Z from the post time stamp
  postDateTime2[1] = postDateTime2[1].replace('Z','');


  //split the post date/time into sperate variables
  var postDate = postDateTime2[0]; // date
  var postTime = postDateTime2[1]; // time

  //split up the post time into hours, minutes, seconds
  var postTimeSplit = postTime.split(":");
  var postTimeHour = postTimeSplit[0];
  var postTimeMinutes = postTimeSplit[1];
  var postTimeSeconds = postTimeSplit[2];

  //split the date to have year, month, date separate
  var postDateSplit = postDate.split("-");

  //split the post date to year, month, date
  var postYear = postDateSplit[0];  //year
  var postMonth = postDateSplit[1]; //month
  var postDate2 = postDateSplit[2]; //date

  //get the current hour, minutes, seconds in UTC time.
  var hours = now.getUTCHours();
  var minutes2 = now.getUTCMinutes();
  var seconds2 = now.getUTCSeconds();



  //get the difference in years between post time and response time
  var responseYear = Math.abs(now.getUTCFullYear() - postYear); 
  //get the difference in months between post time and response time
  var responseMonth = Math.abs(mm - postMonth); 
  //get the difference in days between post time and response time
  var responseDate = Math.abs(now.getUTCDate() - postDate2); 
  //get the difference in hours between post time and response time
  var responseHour = Math.abs(now.getUTCHours() - postTimeHour);
  //get the difference in minutes between post time and response time 
  var responseMinutes = Math.abs(now.getUTCMinutes() - postTimeMinutes);
  //get the difference in seconds between post time and response time
  var responseSeconds = Math.abs(now.getUTCSeconds() - postTimeSeconds); 

  Math.round(responseSeconds); // round the seconds to up to 2 decimal (doesn't work as expected)

So like I said, it works but if the time difference is more than one hour, it's starts giving weird outputs. For example if the real time difference has been only 38 minutes and the current time is an hour ahead, it will count it as 1 hours and 22 minutes.

Any suggestions how I can do this better?

SS113
  • 548
  • 1
  • 11
  • 21
  • To give a better explanation of the problem, look at this example: 2015-04-23 23:33:17 - 2015-04-23 23:23:49 = output it gives is 10 minutes and 32.005 seconds but in reality it's 0:09:28 – SS113 Apr 23 '15 at 23:36
  • 1
    Instead of splitting the strings use the [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) functions to get the parts you need. What might be easier is using `.getTime()` to get the millisecond ticks and do a simple difference on two integers then determine whole time units from the milliseconds. – Jasen Apr 23 '15 at 23:44
  • Jasen, I can do that for the current date/time but the date/time I want to subtract it from is formatted as an RFC 3339 time stamp and I can't change that. Maybe I can convert my current time in that RFC 3339 time stamp and then subtract them? – SS113 Apr 23 '15 at 23:49
  • 2
    You can parse that string into a Date: `new date("2015-04-23T22:23:32.902Z")` – Jasen Apr 23 '15 at 23:51

1 Answers1

3

So after some more research and thanks to Jasen, it was easier to convert my current time to a RFC 3339 time stamp and then find the difference that way in milliseconds and convert it back to a date. I also did some additional formatting for readability. Here's my final code:

//current time in RFC 3339 timestamp
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
    + pad(d.getUTCMonth()+1)+'-'
    + pad(d.getUTCDate())+'T'
    + pad(d.getUTCHours())+':'
    + pad(d.getUTCMinutes())+':'
    + pad(d.getUTCSeconds())+'Z'
}

var d = new Date();
var currentTime = ISODateString(d);

//assign vars for current hour, minutes, seconds in UTC time.
var hours = d.getUTCHours();
var minutes = d.getUTCMinutes();
var seconds = d.getUTCSeconds();

//parse both time stamps into dates
var finalCurrentTime = Date.parse(currentTime);
var finalPostDateTime = Date.parse(postDateTime);

//find the difference between the original post date/time and the current date/time (in milliseconds)
var responseTimeFinal = Math.abs(finalCurrentTime - finalPostDateTime);


function dhm(ms){
var days2 = Math.floor(ms / (24*60*60*1000));
var daysms=ms % (24*60*60*1000);
var hours2 = Math.floor((daysms)/(60*60*1000));
var hoursms=ms % (60*60*1000);
var minutes2 = Math.floor((hoursms)/(60*1000));
var minutesms=ms % (60*1000);
var sec = Math.floor((minutesms)/(1000));

days2 = (days2 < 10) ? "0" + days2 : days2;
hours2 = (hours2 < 10) ? "0" + hours2 : hours2;
minutes2 = (minutes2 < 10) ? "0" + minutes2 : minutes2;
sec = (sec < 10) ? "0" + sec : sec;

  //format day
  if (days2 === "00"){
    days2 = "";
  } else if (days2 === "01"){
    days2 = days2 + " day, ";
  } 
  else if (days2 > "01"){
    days2 = days2 + " days, ";
  }

  //format hours
  if (hours2 === "00"){
    hours2 = "";
  }   
  else if (hours2 === "01"){
    hours2 = hours2 + " hour, ";
  } 
  else if (hours2 > "01"){
    hours2 = hours2 + " hours, ";
  }

  //format minutes
  if (minutes2 === "01"){
    minutes2 = minutes2 + " minute, ";
  } 
  else if (minutes2 > "01"){
    minutes2 = minutes2 + " minutes, ";
  }

  //format seconds
  if (sec === "01"){
    sec = sec + " second";
  } 
  else if (sec > "01"){
    sec = sec + " seconds";
  }

return days2+""+hours2+""+minutes2+""+sec;
}

//pass the milliseconds from responseTimeFinal into the dhm function to convert it back to a date
var timeDifference = dhm(responseTimeFinal);

console.log(timeDifference);  // our final result that works!
SS113
  • 548
  • 1
  • 11
  • 21