开发者

How does the following code regarding timespan to datetime really work?

I have HH:mm:ss from database with HH is more than 100. I have data like that for about 3 rows.开发者_Python百科

I want to calculate the total show in HH:mm:ss.

So, I split that HH:mm:ss to second and I get total second. And I work like this.

TimeSpan t = TimeSpan.FromSeconds(TTTot); 
string answer="";
answer = string.Format("{0:D2}:{1:D2}:{2:D2}", t.Hours, t.Minutes, t.Seconds);
answer = string.Format("{0:D2}-{1:D2}:{2:D2}:{3:D2}", t.Days, t.Hours, t.Minutes, t.Seconds);    
answer = string.Format("{0:D5}:{1:D2}:{2:D2}",t.TotalHours, t.Minutes, t.Seconds);

The first line of the answer is my original code. I only saw around 15 hours while there are around 130 in total values.

So I upgraded to second line of answer which shows together with day. That works.

However, I would like to show total hour. So i modify the code to the third line where I get the exception as

Invalid format exception

I wonder how to twist to get the result I want. HH:mm:ss with HH may b in hundred values.


This MSDN Library page is very relevant. It says this about the D or d format specifier:

The "D" (or decimal) format specifier converts a number to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative. This format is supported only for integral types.

Which is a problem, TimeSpan.Hours returns a double value, not an integral value, like TimeSpan.Minutes does. You can fix this problem by truncating (not rounding) the double value, like this:

answer = string.Format("{0:D5}:{1:D2}:{2:D2}",
   (int)t.TotalHours, t.Minutes, t.Seconds);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜