# Calculate time (in hours and minutes) from given rate of payment (in VB.net)

How can I generate the time (in hours and minutes) from given rate (for payments)? The user will need to enter the payment and the rate to get the total time duration. How can this mission be accomplished?

**example:**

rate = $2.00 per hours payment = $5.00

result:

duration = 02 h 30 minutes

Thank you.

## Answers

Use TimeSpan to simplify your code...

Private Function GetDuration(hourlyRate as decimal, payment as decimal) As TimeSpan return TimeSpan.FromHours(payment / hourlyRate) End Function ' ... Dim duration = GetDuration(2, 5) Console.WriteLine("{0} hours {1} minutes", duration.Hours, duration.Minutes)

**Fiddle: http://dotnetfiddle.net/2tvYMK**

Once you have the decimal point representation of time in hours (ie. 2.5), all you have to do is:

- take the integer part - that's the number of full hours;
- subtract the integer part from total and multiply by 60; that's the number of minutes

Something along these lines should work:

Dim hours as Integer Dim minutes as Integer Dim time as Double time = payment / rate hours = CInt(time) minutes = CInt((time - hours) * 60) Console.WriteLine("duration = {0} h {1} minutes", hours, minutes)

hours = payment \ rate; minutes = (payment/rate - hours) * 60;

Use a TimeSpan structure. It will do the calculations of hours and minutes for you.

Dim rate As Double = 2.0 Dim payment As Double = 5.0 Dim time = TimeSpan.FromHours(payment / rate) Dim duration = [String].Format("{0:00} h {1:00} minutes", time.Hours, time.Minutes) ' ==> "02 h 30 minutes"

You can also use the Decimal type when working with money. It has the advantage of not introducing additional rounding errors when converting from and to binary formats. However, TimeSpan.FromHours expects the hours as Double. Therefore Double seems appropriate for this little example.