Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Convert minutes into hours and minutes 2

Status
Not open for further replies.

DoctorGonzo

Programmer
Jan 23, 2004
48
0
0
GB
Hi guys,

Need help with a javascript / maths problem.

I have a field which contains a number of minutes.

I need to convert this into hours and minutes though.

If I simply divide the field by 60, this gives me a DECIMAL ie. 350 (mins) divided by 60 returns 5.83 hours... but what needs to be returned is 5 hours 50 minutes.

Can anyone help with this? I'm thinking I will pass the minutes value to some sort of function.....

Gonzo
 
[tt]
var s="350"; //get from the field say
var t;
if (/^\d*\.{0,1}\d*$/.test(s)) { //decimal separator "."---know your users
t=Math.floor(parseInt(s,10)/60)+" hours "+((parseFloat(s,10)%60).toFixed(0))+" minute(s)";
} else {
t="Not a number." //or whatever you want to show or do
}
[/tt]
 
Another way, without validation

Code:
function toHoursAndMinutes(minutes) {
var mins = minutes%60; //modulus dividing by 60
var hrs = (minutes - mins)/60; //Now you get an integer division
alert(hrs+":"+mins);
}

Cheers,
Dian
 
Amendment

Upon re-reading my post, I want to close a catch related to rounding.
[tt]
var s="350"; //get from the field say
var t;
if (/^\d*\.{0,1}\d*$/.test(s)) { //decimal separator "."---know your users
[blue]t=Math.floor((parseFloat(s,10).toFixed(0))/60)+" hours "+(parseFloat(s,10).toFixed(0))%60+" minute(s)"[/blue];
} else {
t="Not a number." //or whatever you want to show or do
}
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top