Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert timespan method to decimal?

Tags:

c#

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.

like image 977
John Avatar asked Nov 20 '11 01:11

John


People also ask

How to Convert TimeSpan to Decimal in c#?

time2=DateTime. Parsee(10:00AM); TimeSpan ts = time2. Subtract(time1);//ex.. ts= 10.00.

How do you convert TimeSpan to hours?

A TimeSpan value can be represented as [-]d. hh:mm:ss. ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second. The value of the Hours property is the hours component, hh.


2 Answers

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.

like image 64
SLaks Avatar answered Nov 01 '22 00:11

SLaks


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");
like image 44
Jay Avatar answered Oct 31 '22 23:10

Jay