Progressive and cumulative hours counter with days

9

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

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

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

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 do not understand js, but I think it's the best solution, I found an interesting script of timer , I've already adapted some of the needs, but I can not apply more than one input causing the code to react dynamically.

    
asked by anonymous 07.12.2015 / 13:14

1 answer

2

Well folks. To make calculations with hours, you have to turn the time to a number that corresponds to the smallest significant unit you are going to work with. For example, if you need the seconds, transform it into seconds: HourSeconds = hours * 3600 + minutes * 60+ seconds. Then calculate the time by calculating timeTotal = hrEmSegFinal - Initial Time. Well, sorry, I do not understand anything from 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's possible in PHP as well. The first takes the UNIX time (all milliseconds since 01/01/1970 summed) and calculates the time interval. And just start to stay by clicking on the stop / continue buttons that the time intervals are being added in the variable time1 Cumulative. The second, the calculation is done from the time typed into text fields and these intervals are being accumulated in variable time2 Cumulative, in minutes. Oh, do not forget, that this method aims to be simple and didactic. If this interval involves midnight (change of date), it must be added 24 hours at the end time (can be done by placing an if if the start time is greater than the end time). Ah, because they are in javascript, they can have problems if the client machine time 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;//Do1ométodo:emmilissegundostempo2Acumulado=0;//Segundométodo:emminutoshoraInicial;functionsetZero(num){//põezeroaesquerda,seonumeroformenorque10.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>
    
12.03.2016 / 06:34