Progressive and cumulative hour counter with days

Asked

Viewed 2,058 times

9

I have a project where I must accumulate hours worked of a service in a project, it must store in the bank the hours/days.

So when started, if there is no previous time starts from scratch, but if there has been a step previously it should count from that and time and accumulate, saving later in the bank.

Until then the script is working, but now I need to make it dynamic so that the report appears more than one project showing the execution time.

JS

<script language=JavaScript>
    <!-- begin
    function getSecs(sDias, sHors, sMins, sSecs, campo, tempo) {
        sSecs++;
        if (sSecs == 60) {
            sSecs = 0;
            sMins++;
            if (sMins <= 9) sMins = sMins;
        }
        if (sMins == 60) {
            sMins = 0;
            sHors++;
            if (sHors <= 8) sHors = sHors;
        }
        //converte para horas trabalhadas, se fossem dias normais seria 24h if(sHors==24){
        if (sHors == 8) {
            sHors = 0;
            sDias++;
        }
        //corrige com 2 digitos
        if (sSecs <= 9) sSecs = "0" + sSecs;
        if (sMins <= 9) sMins = "0" + sMins;
        if (sHors <= 9) sHors = "0" + sHors;
        if (sDias <= 9) sDias = "0" + sDias;
        document.getElementById(campo)
            .innerHTML = sDias + ":" + sHors + ":" + sMins + ":" + sSecs;
        setTimeout("getSecs(" + sDias + ", " + sHors + ", " + sMins + "," + sSecs + ", '" + campo + "')", 1000);
        form1.tempo.value = sDias + ":" + sHors + ":" + sMins + ":" + sSecs;
    }
    //-->
</script>

PHP

<?php
    var_dump($_POST);
    $data1 = '0,1,59,55';
    $data2 = '0,7,59,55';
?>

HTML

<script>
    setTimeout("getSecs(<?= $data1 ?>, \"campo1\",'tempo;')", 1000);
</script>

<hr>

<form action="" method="POST" enctype="multipart/form-data" role="form" name="form1">
    <input type="text" id="campo1" name="tempo" value="">
    <hr>
    <input type="submit" value="Enviar" class="btn btn-primary" />

I don’t know about you, but I think it’s the best solution, I found a script interesting of timer, I’ve adapted some of the needs, but I can’t apply more than one input making the code react dynamically.

  • 2

    I think it would be nice using ajax, then you don’t even need the timer. Also I advise you to use lib momentJs, it facilitates a lot of calculations with date.

  • Man how do I do it? Srsrsrsrsrrs

  • Good to work with ajax?

  • n. It took me 2 days to make a 4 script merge to do this rssrsr

  • You managed to solve?

  • I haven’t been able to

  • Uses a plugin called Final Countdown. My colleague had to do exactly the same thing. I taught him to do with the LocalStorage to store where time "stopped" to proceed later from the same point.

  • 1

    It was bad, actually I used the wrong plugin. What he used calls Flipclock. Now you know two :)

  • I’m gonna test, vlw

  • 2

    If you solved the problem, you can close the question.

  • Solved your problem?

Show 6 more comments

1 answer

2

Very personal. To make calculations with hours, you need to turn the hour into a number that corresponds to the smallest significant unit you will work with. For example, if you need seconds, turn it into seconds: timeEmSeconds = hours*3600 + minutes*60 + seconds.
Then calculate the time by doing the calculation timeTotal = hrEmSegFinal - hrEmSegInitial.
Well, sorry, I don’t know anything about PHP, I started with Java and now I work with Nodejs. I have here two methods in javascript, which in Java, logically, with small adaptations, also work. I believe it is also possible in PHP.
The first takes UNIX time (all milliseconds since 01/01/1970 summed) and calculates the time interval. And just start by clicking on the stop/continue buttons that the time intervals are being summed in the variable temp.
The second, the calculation is done from the time typed in text fields and these intervals are accumulated in the variable temp2Acumulated, in minutes. Ah, do not forget, that this method aims to be simple and didactic. If this interval involves midnight (date change), it must be added 24 hours to the final hour (it can be done by placing an if the start time is longer than the end time). Ah, because they are in javascript, they may present problems, if the time of the client machine is not correct. I hope it can be adapted to PHP, but in Nodejs it works because this is your programming language.

HTML + Javascript

<!DOCTYPE html>
<html>
   <head>
       <title>Contador acumulativo de tempo</title>
       <meta charset="UTF-8">
       <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
        <script>
            tempo1Acumulado = 0; // Do 1o método: em milissegundos
            tempo2Acumulado = 0; // Segundo método: em minutos
            horaInicial;

            function setZero(num){ // põe zero a esquerda, se o numero for menor que 10.
                n = num.toString();
                   if(n.length < 2) {
                       n = "0" + n;
                    }
                    return n;
               }

            // msParaHora: Vai escrever o resultado no formato hh:mm:ss 
            function msParaHora(ms) {
                var horas = Math.floor(ms/3600000);    //  parte inteira da divisão
                var restoh = ms % 3600000;              //  resto da hora, em ms
                var minutos = Math.floor(restoh/60000);
                var restom = restoh % 60000;
                var segundos = Math.floor(restom/1000);
                return setZero(horas) + ":" + setZero(minutos) + ":" + setZero(segundos); 
            }
            /*Inicia a contagem do tempo*/
            function getHoraInicio(){ //Inicia a contagem 
                 horaInicial = Date.now(); 
                 $("#ta").text("Acumulado no inicio : " + tempo1Acumulado + " ms = " + msParaHora(tempo1Acumulado));
                 $("#info").text("Contagem em andamento...");
                 $("#btnIniciar1").prop("disabled", true);
                 $("#btnIniciar1").val("Continuar");
                 $("#btnFim1").prop("disabled", false);
            }
            /*suspende a contagem de tempo */
            function paraContador(){ //Termina a contagem do intervalo 
                 var horaFim = Date.now(); 
                 var intervalo = horaFim - horaInicial;
                 tempo1Acumulado += intervalo;

                 $("#info").text("duração do ultimo intervalo: " + intervalo);
                 $("#ta").text("Contagem Parada, Total acumulado:" + tempo1Acumulado 
                    + " ms = " + msParaHora(tempo1Acumulado));
                 $("#info").text("Duração do último intervalo: " + intervalo + "ms = " +
                       msParaHora(intervalo));
                 $("#btnIniciar1").prop("disabled", false);
                 $("#btnFim1").prop("disabled", true);

            }
            //*******Segundo Modo --- quando a hora é inserida manualmente *********************
            // **** O tempo é calculado em minutos, mas se por algum motivo precisar de 
            // mais precisão, basta adaptar os cálculos

            function minutosParaHora(minutos){
                var horas = Math.floor(minutos/60); // inteiro da divisão = horas
                var minuts = minutos % 60;      // resto da divisão = minutos
                return setZero(horas) + ":" + setZero(minuts);
            }

            function addTempo(){ // em minutos trabalhados
                var stri = $("#hIni").val(); // pega o valor do inicio
                var hrIni = stri.split(":"); // separa a hora dos minutos pelo ":", e coloca num array 
                // obter a hora de início, em minutos
                var hMinInic = parseInt(hrIni[0])*60 + parseInt(hrIni[1]);

                var strt = $("#hTerm").val(); // pega o valor do témino
                var hrTerm = strt.split(":"); // separa a hora dos minutos pelo ":", e coloca num array 
                // obter a hora de término, em minutos
                var hMinTerm = parseInt(hrTerm[0])*60 + parseInt(hrTerm[1]);

                var IntervaloDeTempo = hMinTerm - hMinInic;  // o Intervalo de tempo em minutos

                tempo2Acumulado += IntervaloDeTempo;       // adiciona este invervalo ao acumulado

               /*****************Exibe o resultado**/
               $("#ta2").text("Total Acumulado: " + tempo2Acumulado + " minutos = " 
                 + minutosParaHora(tempo2Acumulado) + ". Duração a última jornada: " 
                     +  IntervaloDeTempo + " minutos = " + minutosParaHora(IntervaloDeTempo));

             }

        </script>

    </head>
    <body>
        <h1>Contagem de Tempo</h1>
        <fieldset>
            <legend>Método 1- A partir da hora do Sistema </legend>
                  <p id="ta">Total Acumulado: 0</p>
                  <p id="info">Clique no botão iniciar: 0</p>
                  <input id="btnIniciar1" type="button" value="Iniciar" onclick="getHoraInicio()" title="Iniciar neste momento"/>
                  <input id="btnFim1" type="button" value="Parar" onclick="paraContador()" title="Terminar agora" disabled="disabled"/>
        </fieldset>
        <fieldset>
            <legend>Método 2- Apartir da hora digitada</legend>
                  <p id="ta2">Total Acumulado: 0</p>
                  <label>Hora Início</label>
                  <input type="text" id="hIni" value="14:17" /> <br/>
                  <label>Hora Término</label>
                  <input type="text" id="hTerm" value="17:30" /><br/>
                  <input id="btnCalc" type="button" value="Adicionar o Intervalo de Tempo" onclick="addTempo()" title="Terminar agora"/>
        </fieldset>
    </body>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.