Simon Tindall Simon Tindall - 3 months ago 19
C# Question

Get date difference for differences > 24 hours

I am displaying on my web app the difference between two dates in

hh:mm:ss
format using the following code:

double durationSeconds = (EndDateTime - StartDateTime).TotalSeconds;
TimeSpan seconds = TimeSpan.FromSeconds(durationSeconds);
string duration = seconds.ToString(@"hh\:mm\:ss\:fff");
litDuration.Text = duration;


This only works for differences less than 24 hours but I would like the hour counter to display higher. e.g. using the following DateTimes

StartDateTime = 2016-08-25 15:00:00
EndDateTime = 2016-08-27 15:28:30


The difference in hh:mm:ss format should be
48:28:30
but is currently displaying
00:28:30
.

Any help is greatly appreciated

Answer

How about doing it this way?

string duration =
    String.Format(
        @"{0}:{1:mm\:ss\:fff}",
        seconds.Days * 24.0 + seconds.Hours,
        seconds);
Comments