Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

424
Visualizações
Calculate time difference in hh:mm:ss with simple javascript/jquery

I have two input field for the time start and time end and there is another field for the difference which is the Call Duration. I want the result on the field to be in this format = 00:21:03

<div class="inline_divider">
  <label for="form_qa_startcall" class="qaw_form_label3">Start of Call</label>
  <input type="text" id="form_qa_startcall" class="qaw_form_input3" placeholder="eg. 11:36:47 PM" maxlength="11">
</div>
<div class="inline_divider">
  <label for="form_qa_endcall" class="qaw_form_label3">End of Call</label>
  <input type="text" id="form_qa_endcall" class="qaw_form_input3" placeholder="eg. 11:46:47 PM" maxlength="11">
</div>
<div class="inline_divider">
  <label for="form_qa_callduration" class="qaw_form_label3">Call Duration</label>
  <input type="text" id="form_qa_callduration" class="qaw_form_input3" placeholder="eg. 00:01:10" maxlength="8">
</div>

I am having a hardtime getting the result due to the "AM/PM" formatting. I have found a similar question like this but he is using "momentjs". As much as possible, I don't want to use any plugins, just a plain javascript or from jquery will do. This is the code I got working, I am getting the result (0:21:3) but I need it to be two digits for hours, minutes, and seconds (00:21:03).

$("#form_qa_endcall").on('keyup',function(){
  var callStart = $('#form_qa_startcall').val();
  var callEnd = $('#form_qa_endcall').val();
  var timeStart = new Date("01/01/2007 " + callStart);
  var timeEnd = new Date("01/01/2007 " + callEnd);

    function datediff(fromDate,toDate,interval) {
        var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
        fromDate = new Date(fromDate);
        toDate = new Date(toDate);
        var timediff = toDate - fromDate;

        if (isNaN(timediff)) return NaN;
        switch (interval) {
            case "years": return toDate.getFullYear() - fromDate.getFullYear();
            case "months": return (
                ( toDate.getFullYear() * 12 + toDate.getMonth() )
                - 
                ( fromDate.getFullYear() * 12 + fromDate.getMonth() )
            );
            case "weeks"  : return Math.floor(timediff / week);
            case "days"   : return Math.floor(timediff / day);
            case "hours"  : return Math.floor(timediff / hour);
            case "minutes": return Math.floor(timediff / minute);
            case "seconds": return Math.floor(timediff / second);
            default: return undefined;
        }
    }
    var seco = datediff(timeStart, timeEnd, 'seconds') % 60;
    var minu = datediff(timeStart, timeEnd, 'minutes') % 60;
    var hour = datediff(timeStart, timeEnd, 'hours');

    $('#form_qa_callduration').val(hour + ":" + minu + ":" + seco);
});
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You could use this code:

function diff(a, b) {
    function toTime(a) {  
        return Date.parse('1970-01-01 ' + a.substr(0,8)) / 1000
             + (a.includes('PM') && (12*60*60));
    }
    var d = toTime(b) - toTime(a);
    return d >= 0 ? new Date(0,0,0,0,0,d).toTimeString().substr(0,8) : '';
}

$('.qaw_form_input3').on('input', function () {
    $('#form_qa_callduration').val( 
        diff($('#form_qa_startcall').val(), $('#form_qa_endcall').val()));
}).click();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inline_divider">
  <label for="form_qa_startcall" class="qaw_form_label3">Start of Call</label>
  <input type="text" id="form_qa_startcall" class="qaw_form_input3" placeholder="eg. 11:36:47 PM" maxlength="11">
</div>
<div class="inline_divider">
  <label for="form_qa_endcall" class="qaw_form_label3">End of Call</label>
  <input type="text" id="form_qa_endcall" class="qaw_form_input3" placeholder="eg. 11:46:47 PM" maxlength="11">
</div>
<div class="inline_divider">
  <label for="form_qa_callduration" class="qaw_form_label3">Call Duration</label>
  <input type="text" id="form_qa_callduration" class="qaw_form_input3" placeholder="eg. 00:01:10" maxlength="8" readonly>
</div>

As the duration will be updated by changes to the other two input values, it would be a good idea to make the duration input read-only, by adding the readonly attribute.

about 4 years ago · Santiago Trujillo Relatório

0

Assuming you get it as strings, you can roughly do the following.

var str1 = "11:31:51 AM";
var str2 = "11:52:54 AM";

str1 = str1.split(':');
str2 = str2.split(':');

if(str1[2].split(' ').pop() != str2[2].split(' ').pop()) { // one is AM other is PM
   str1[0] = parseInt(str1[0])+12;
}

var finalStr = m(str1[0], str2[0])+":"+m(str1[1], str2[1])+":"+m(str1[2], str2[2]);

console.log(finalStr);

function m(n1,n2) {
  return Math.abs(parseInt(n1)-parseInt(n2));
}

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda