javascripthourminute

How to convert hours in minutes in javascript HH:MM to MM?


I want to convert HH:MM to MM I want to use minutes in below code but It can't convert 14:30 to 858 as you can see result here in fiddle minutes but it converts 14.3 to minutes if you put 14.3 in fiddle code instead of 14.30.

I am converting hrs. in minutes than I am Lessing 240 minutes from minutes I got How can I convert this hrs. in minute. below is the code I am trying to convert hours to minutes

NOTE: hours can be can be any Time from 0 to 23 it could be 2:30 or it could be 10:30

function convertHourstoMinute(hours) {
     return Math.floor(hours * 60);
    }
    let hrs = convertHourstoMinute(14:30); // convert hours into minutes javascript
   console.log( "javascript convert hours to minutes :- " + hrs ); 

            let minutes = hrs * 60;
            console.log(minutes)
            let callback_time = minutes - 240
            console.log(callback_time)
            let call_back = callback_time / 60
            console.log(call_back)

Solution

  • A few things are incorrect in your code first you can not pass 14:30 it has to be "14:30" then 14:30 * 60 is not a valid expression it has to be 14 * 60 + 30 and you dont need Math.floor because you are not passing decimal numbers if you want to pass decimal number then you have to use 14.5 instead 14:30

    function convertH2M(timeInHour){
      var timeParts = timeInHour.split(":");
      return Number(timeParts[0]) * 60 + Number(timeParts[1]);
    }
    
    var timeInMinutes = convertH2M("14:30");
    console.log(timeInMinutes);

    If you want to pass decimal numbers instead of 14:30 then this example works

    function convertH2M(timeInHour){
      return Math.floor(timeInHour * 60);
    }
    
    var timeInMinutes = convertH2M(14.5);
    console.log(timeInMinutes);