-4

I am getting total hour from this code :

string date = Request.Form[DFrom.UniqueID];
string date1 = Request.Form[DTo.UniqueID]; ;

DateTime start = DateTime.ParseExact(date, "MM/dd/yyyy hh:mm tt", null);
DateTime end = DateTime.ParseExact(date1, "MM/dd/yyyy hh:mm tt", null);
totaltime = (start - end).TotalHours;

Output will be like this :

25.44535

I want to convert the total hours to formatted time like this for example : 44:12:00

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Ali Alzahrani
  • 529
  • 1
  • 6
  • 29

3 Answers3

2

Since you have already a TimeSpan, you can format it like;

var ts = (start - end);
Console.WriteLine("{0:00}:{1:00}:{2:00}", ts.Days, ts.Hours, ts.Minutes); // 01:01:26

Remember, these Days, Hours and Minutes properties returns whole hours as an int. If you look for their fractional parts also, you can use theirs TotalXXX properties as well.

With .NET Framework 4.0, Custom TimeSpan Format Strings introduced. If you have this version or higher, you can use this custom format as well like;

Console.WriteLine("{0:dd\\:hh\\:mm}", ts);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

Propably you don't want to convert this to totalHours. You can simply return a TimeSpan totaltime = (start - end)

Marcin J
  • 378
  • 4
  • 15
0

If you would like to have in format hh:mm:ss, you can do like this:

TimeSpan ts = start- end;
string st = String.Format("{0:00}:{1:00}:{2:00}", ts.Days*24+ts.Hours, ts.Minutes, ts.Seconds);
Kodre
  • 181
  • 6