TimeSpan\ConvertingResult

  • Thread starter Thread starter gh
  • Start date Start date
G

gh

I have 2 columns in a grid where the user enters a begining time(TI) and
at the end of the day an end time(TO). I then want to take the TO - TI
to get the difference and display it as hours and minutes. If the
result is 7 hours and 45 minutes I would like it to be able to display
it 2 ways, as 7.45 or 7.75, if it was 8 hours then display 8.00. I have
the code below to do the subtraction, but I am not able to get the
result converted to a double.

TI = colTimeIn;
TO = colOut;
TimeResult = TO.Subtract(TI);
double aTime = Convert.ToDouble(TimeResult);<--- Errors here

How would I get the the conversion and be able to store it as a double?


TIA
 
gh,

You will have to do it manually. Basically, you have to say:

double aTime = TimeResult.Hours + (TimeResult.Minutes / 60);

Hope this helps.
 
There are various ways you could do this; following are just examples. Note
that I have used TotalHours (not Hours) to avoid the scenario where it has
taken over a day, hence test case of 38 hours.

TimeSpan ts = new TimeSpan(38, 45, 23);
Console.WriteLine("{0}:{1}:{2}:{3}", ts.Days, ts.Hours,
ts.Minutes, ts.Seconds);
Console.WriteLine(ts.TotalHours); // simplest (decimal) - but
includes seconds & ms etc

// round to hours and minutes only (is there an easier way?)
int hours = (int)Math.Floor(ts.TotalHours), minutes =
ts.Minutes;
TimeSpan ts2 = new TimeSpan(hours, minutes, 0);
Console.WriteLine(ts2.TotalHours); // decimal number of hours

Console.WriteLine("{0}.{1}", hours, minutes); // hours.minutes
Console.ReadLine();

Hope something in there is useful.

Marc
 
If all you're looking for is that format, like 7.45 or 8.00 as a
*string*, you could always just use

DateTime.Now.ToString("H.mm")

for example.

Just to provide another "take" on your question.

Scott
 
A TimeSpan subtracted from another TimeSpan yields a TimeSpan. A TimeSpan is
not a double. It is a TimeSpan. It represents a number of ticks. You can
extract Years, Months, Days, Hours, Minutes, Seconds, and Milliseconds from
it using its various properties.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
You can lead a fish to a bicycle,
but it takes a very long time,
and the bicycle has to *want* to change.
 
gh,

TimeSpan ts = new TimeSpan(38, 45, 23);
double dResult = ts.TotalMinutes/60; // divide by # minutes in an hour

Dave
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top