Convert sum of minutes to hours format (eg 70min = 01:10) with jquery

Asked

Viewed 505 times

0

I have the following script that takes the hours and minutes of each day of the week, where the variables that start with m are the minutes of each day of the week (coming from a select) and those beginning with h are of hours.

I’m taking the values of hours, multiplying by 60 to take the minutes and adding up with all the minutes and I have at the end, the sum in minutes.

How do I convert these minutes into hours?

Ex: 70minutes would result 1:10

<script>
  $(document).ready(function(){
    $("select").change(function(){
      //VARIAVEIS MINUTOS
      var mseg = parseInt($("#mseg").val());
      var mter = parseInt($("#mter").val());
      var mqua = parseInt($("#mqua").val());
      var mqui = parseInt($("#mqui").val());
      var msex = parseInt($("#msex").val());
      var msab = parseInt($("#msab").val());
      var mdom = parseInt($("#mdom").val());
      var totalminutos = mseg + mter + mqua + mqui + msex + msab + mdom;
      //VARIAVEIS HORAS
      var hseg = parseInt($("#hseg").val());
      var hter = parseInt($("#hter").val());
      var hqua = parseInt($("#hqua").val());
      var hqui = parseInt($("#hqui").val());
      var hsex = parseInt($("#hsex").val());
      var hsab = parseInt($("#hsab").val());
      var hdom = parseInt($("#hdom").val());
      var totalhoras = (hseg + hter + hqua + hqui + hsex + hsab + hdom) * 60;
      var total = (totalhoras + totalminutos);
      $("#total").val(total);
    });
  });
</script>

1 answer

3


You can create a function that will receive the value in minutes, will use the function Math.floor to remove the entire part and a mod (operator %) to get the rest of the split by 60:

const converter = (minutos) => {
  const horas = Math.floor(minutos/ 60);          
  const min = minutos % 60;
  const textoHoras = (`00${horas}`).slice(-2);
  const textoMinutos = (`00${min}`).slice(-2);
  
  return `${textoHoras }:${textoMinutos}`;
};

console.log(converter(70));

  • gave, but did not give...rs, I changed the part of the console.log to bring the result: var total = convert(total); $("#total"). val(total);. It calculates, but gives an error: jquery.min.js:2 The specified value "0:10" is not a Valid number. The value must match to the following regular Expression: -?( d+| d+. d+|. d+)([ee][-+]? d+)?

  • @Leandromarzullo the input in which you will put the result is number?

  • puts, was that right...rs, I switched to text and it was normal, just one more little detail, has to round 2 house? ex: 0:2 be 0:02 or this goes with mask

  • @Leandromarzullo added

  • 1

    Perfect, worked right, thanks!

Browser other questions tagged

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