简体   繁体   中英

c# convert days to hh:mm in timespan

while calculate the sum of all span it shows result in days (dd:HH:mm) .question is how i get the sum only in HH:mm format.how i convert the days in hour

          TimeSpan Span1 = TimeSpan.Parse(mnts1);
          TimeSpan Span2 = TimeSpan.Parse(tuts1);
          TimeSpan Span3 = TimeSpan.Parse(wdts1);
          TimeSpan Span4 = TimeSpan.Parse(thts1);
          TimeSpan Span5 = TimeSpan.Parse(frts1);
          TimeSpan Span6 = TimeSpan.Parse(stts1);
          TimeSpan Span7 = TimeSpan.Parse(suts1);
          TimeSpan  rf = Span1 + Span2 + Span3 + Span4 + Span5 + Span6 + Span7; 

Format it manually:

Console.WriteLine("{0:00}:{1:00}", rf.TotalHours, rf.Minutes);

You can still use string formatting by calling string.Format :

string result = string.Format("{0:00}:{1:00}", rf.TotalHours, rf.Minutes);
Console.WriteLine(result);

There doesn't seem to be a format option for getting the total hours out of a TimeSpan . Your best bet would be to use the TotalHours property instead:

Console.WriteLine("{0:00}:{1:00}", (int)rf.TotalHours, rf.Minutes);

TotalHours returns a double as it includes the fractional hours so you need to truncate it to just the integer part.

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