Here, I included my time difference code, but I am getting NaN error.
How to do time difference in my code.
I need my output like,
03 Hrs : 30 Mins

Here is my code:

/////Calculate time duration start///////
/*function calculate_Duration()
//var start_time = document.getElementById('start_time').value;
//var end_time = document.getElementById('end_time').value;
var start_time = "10:00 AM";
var end_time = "01:30 PM";
var stSplit_Start = start_time.split(" ");
var stHour_Start = stSplit_Start[0]+":"+"00";

var stFrmt_Start = stSplit_Start[1];

if(stHour_End > stHour_Start)
res =  (stHour_End - stHour_Start)/1000*60*60*24;
alert("Can`t Calculate Duration");


/////Calculate time duration end////////

datewill be any date, I do not want date with time calculation

Recommended Answers

All 4 Replies

You will NEED date when you calculate time. The reason is that if the time is NOT on the same day, how would you know that? Anyway, you could simply use Date object and manipulate by giving the same date to it. However, you cannot compare times with 2 different date in this case.

Below is a quick and dirty version of time difference in JavaScript (not JQuery). There are differences compared to what you are trying to do.

  1. Return value is in milliseconds
  2. Return -1 if time string is not as expected format ("HH:MM AM/PM")
  3. Return a negative value if time1 is after time2
  4. Both times must be in the same day

Now here is the script...

// Return time diffrence in milliseconds.
// Return -1 if time format is invalid.
// Assuming time1 & time2 are on the same day.
// Assuming time2 is after time1.
function calculateTimeDifferenceInTheSameDay(time1, time2) {
  var sanTime1 = sanitizeTime(time1);
  var sanTime2 = sanitizeTime(time2);
  if (sanTime1=="" || sanTime2=="") { return -1; }

  var date1 = Date.parse(sanTime1);
  var date2 = Date.parse(sanTime2);
  return (date2-date1);

// return date format as 2001-01-01THH:MM:00
//   which is a date format YYYY-MM-DDTHH:MM:SS
// Expecting time string format as HH:MM AM/PM
function sanitizeTime(time) {
  if (!time || !time.match(/^\d{2}:\d{2}\s+[AP]M/i)) { return ""; }
  var hm_mer = time.split(/\s+/);  // getting [HH:MM, Meridian]
  var hm = hm_mer[0].split(/:/);   // getting [HH, MM]
  if (parseInt(hm[0], 10)>11 || parseInt(hm[1], 10)>59) { return ""; }
  var t = hm_mer[1].match(/^P/i) ? (parseInt(hm[0], 10)+12) : hm[0];
  return ("2000-01-01T"+t+":"+hm[1]+":00");

Mr Taywin ,
It shows nothing. I aaplied what you given

Here is the the input/output I tested...

calculateTimeDifferenceInTheSameDay("01:30 pm", "07:15 pm")
// output 20700000
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.