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!

Converting FROM hh:mm to minutes (opposite of last weeks post) 1

Status
Not open for further replies.

DoctorGonzo

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

Tsuji and Diancecht gladly provided me with the code below last week which converts MINUTEs into HOURS and MINUTES in the format hh:mm.... this works perfectly.

EXAMPLE :
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);
}

Brilliant. However, I now have a requirement to do the OPPOSITE of this - ie

1) get a handle to a field where user has entered hh:mm
2) convert this to minutes

i.e. user enters 2:15 and this converts to 135 minutes

probably need to validate to make sure user enters correctly in hh:mm format

can anyone assist? This maths/logic is a big problem for me

Many thanks!

Gonzo
 
Well, I leave validation for anyone who knows regex, but the maths behind this are not really complicated

Would be something like
Code:
var hoursDotMinutes = "2:15";
var fieldArray = hoursDotMinutes.split(":");
var minutes = parseint(fieldArray[0]) + 60*parseint(fieldArray[1]);

Cheers,
Dian
 
Cheers Dian!

I used it in this function - as you can see we just had the * and the + the wrong way around, but I spotted that (as I said my maths is terrible!)

function toMinutes(mins) {
var hoursDotMinutes = mins;
var fieldArray = hoursDotMinutes.split(":");
var minutes = parseInt(fieldArray[0])*60 + parseInt(fieldArray[1]);
}

Many thanks again for all your help.

Gonzo
 
D'oh, my bad. That happens when you don't test things.

Glad you got it to work.

Cheers,
Dian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top