How to compare two time values by pure JavaScript?

Shankar Thiyagaraajan

I try compare two different time to produce the difference time.

var start_time;
var end_time;

start_time = $('#startTime').val();
end_time = $('#endTime').val();

values received are,

start_time : 5:08 PM
end_time   : 6:08 PM

here, how can get a difference time as 1 hr from these time ?

Expected output: 01:00

Is this possible with JavaScript ?

brk

Hope this snippet will be useful

function getDifference(t1, t2) {
  //first splitting by white space. FOr example 5:08 PM will be 5:08 and again splitting by :
  var _t1 = (t1.split(" ")[0].split(":")),
    // converting to number to get the time in minute
    toNum1 = Number(_t1[0]) * 60 + Number(_t1[1]),
    _t2 = (t2.split(" ")[0].split(":")),
    toNum2 = Number(_t2[0]) * 60 + Number(_t2[1]),
    // calulating difference
    dif = toNum2 - toNum1;

  var result = ''
  if (dif % 60 === 0) {
    result = dif % 60 + ':00'
  } else if (dif % 60 < 10) {
    result = Math.floor(dif / 60) + ':0' + dif % 60

  } else if (dif % 60 > 10) {
    result = Math.floor(dif / 60) + ':' + dif % 60
  }
  return result


}

console.log(getDifference("5:08 PM", "6:59 PM"))

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to compare two different time values

how to compare values of two array in javascript

How to compare two values?

How i can compare Two input values at the time of validation

How to compare a variable against two values at the same time?

JavaScript compare two time strings

How compare time on javascript?

How to compare two time picker using javascript or jquery

How to compare two maps by their values

How to compare two numeric values

How to compare values by two rows

How to compare two values in TreeMap?

How to compare two 'wei' values?

How to count time on hover with pure javascript?

How to Loop between two colors in pure JavaScript?

javascript compare two objects and print values

Best way to compare values to two javascript objects

How to compare two variables in javascript

How to compare two string in javascript?

How to get the difference between two values on a time series in JavaScript?

how to compare two values and return the correct answer javascript, and how to call a function only once javascript

How do I compare values from two variables that got their values as result of mapping other variables in JavaScript?

Using Dart / Flutter, how would I compare the values of two textfields to provide a time duration output?

How to compare two data frames and keep rows of the left one based on common values and a time diff in pandas?

how to compare listbox values and table values in javascript?

How to compare two dates and time in Query

How to compare two unix time in flutter?

How to compare two Instant based on the date not time

How to compare two Dates without the time portion?