Link to home
Get AccessLog in
Avatar of ShannonCallahan
ShannonCallahan

asked on

Converting hh:mm:ss to hours decimal in C#

I have a textbox that displays a stopwatch in the format hh:mm:ss with the following:

Stopwatch stopwatch1 = new Stopwatch();

 private void timer1_Tick(object sender, EventArgs e)
        {
            //Set Textbox text equal to elapsed time 
            TimerTextBox1.Text = stopwatch1.Elapsed.ToString("hh\\:mm\\:ss");
      }

Open in new window


Works great. What I am looking for:
After clicking a button,  I want to convert TimerTextBox1.Text to a hour decimal of the time elapsed. Example..  01:30:00 will convert to 1.5 hours.

Thank you for your assistance!
Shannon
ASKER CERTIFIED SOLUTION
Avatar of Craig Wardman
Craig Wardman
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This content is only available to members.
To access this content, you must be a member of Experts Exchange.
Get Access
Avatar of AndyAinscow
Well as there are 60 times 60 seconds in one hour and 6o seconds in a minute then eg. 1 hour 12 minutes and 15 seconds is 1 hour and 12*60+15 seconds which is 1 hour and (12*60+15)/60*60 decimal parts.
Avatar of ShannonCallahan
ShannonCallahan

ASKER

(stopwatch1.Elapsed.TotalMinutes / 60d).ToString();

Works for what I am looking for, however, how to I format it so that it only displays 2 decimal places?

Thank you,
Shannon
SOLUTION
Link to home
membership
This content is only available to members.
To access this content, you must be a member of Experts Exchange.
Get Access
Thank you!!
Why doing math, when a direct conversion is right at hand:

TimerTextBox1.Text = stopwatch1.Elapsed.TotalHours.ToString("N2");

Open in new window

You seemed to have not realised the implications in what I wrote.  
Your initial time shows granularity to 1 second intervals.  Doing what you did will show a much lower level of granularity.  eg. It will show n.00 for quite some time before changing to n.01 which stays like that until going to n.02.....


ps.  Also looking at another question you have asked and referring to a suspicion I voiced in a previous question, consider the following question.  Your boss tells you that instead of 15 'tasks' the user should have up to 30 on the GUI.  Question - how much extra code do you have to write?  (I can do it with zero extra lines of code.  I have no doubt the other experts contributing here could do the same.)