Convert minutes to hours in JavaScript

Convert minutes to hours in JavaScript . Eg: 400 minutes -> 06hrs 40min


<script type="text/javascript">

function minutesToStr(minutes) {
 var sign ='';
 if(minutes < 0){
  sign = '-';
 }

 var hours = leftPad(Math.floor(Math.abs(minutes) / 60));
 var minutes = leftPad(Math.abs(minutes) % 60);

 return sign + hours +'hrs '+minutes + 'min';

}

var hrs = minutesToStr(400);

alert(hrs);            

/*
 * add zero to numbers less than 10,Eg: 2 -> 02
 */
function leftPad(number) {  
    return ((number < 10 && number >= 0) ? '0' : '') + number;
}

</script>

2 comments:

  1. Thanks. That's a great and elegant solution...

    ReplyDelete
  2. can you show a code that can convert from hours to minutes ? i really need that. thanks :)

    ReplyDelete