简体   繁体   中英

How do I convert timespan method to decimal?

Here is my code:

TimeSpan span1 = TimeSpan.FromHours(dtmIn.Value.Hour);
TimeSpan span2 = TimeSpan.FromHours(dtmOut.Value.Hour);
TimeSpan span3 = TimeSpan.FromMinutes(dtmIn.Value.Minute);
TimeSpan span4 = TimeSpan.FromMinutes(dtmOut.Value.Minute);
TimeSpan span5 = span2.Subtract(span1) + span4.Subtract(span3);

lblTotal.Text = Convert.ToDecimal(span5).ToString("#.00");

I get a formatting error for the last line. I can get the label to return as time obviously, but I need it to return as a decimal.

It doesn't make sense to convert a TimeSpan to a decimal, becuase time isn't numeric.

You probably want span5.TotalHours , which is a double that includes the fractional portion.

What is the decimal supposed to represent? Hours and fractions of an hour? You must understand that TimeSpan can't infer this, as TimeSpan could span milliseconds or millennia.

If in fact hours and fractions of an hour, then:

lbTotal.Text = span5.TotalHours.ToString("#.00");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM