Search code examples
c#asp.netdatedatetimedata-access-layer

Converting Difference between two DateTimes in to HH:MM:SS format in asp.net C# Databinding Class


net application in which I needed to subtract two datetimes and display them in HH:MM:SS format. I'm fetching these from data base in mappling class and trying to subtract and convert to string format there. I'm trying in the following way

TimeTook = Convert.ToString(reader.GetDateTimeNullable("COMPLETED_DATE") - reader.GetDateTime("REQUEST_DATE"))

This statement is used in a mapping function and when I convert it into string i'm getting in days HH:MM:SS.ff format but i want to get it in HH:MM:SS format as i'm binding this directly to a label in an user control as follows

 <asp:Label ID="lblTimeTook" runat="server" Text='<%# Bind("TimeTook") %>'></asp:Label>

I want to bind directly the difference between two dates and display them in HH:MM:SS format.


Solution

  • Subtracting two DateTimes returns a TimeSpan which can be easily formatted:

    TimeTook = ( reader.GetDateTimeNullable("COMPLETED_DATE") -
                 reader.GetDateTime("REQUEST_DATE")
               ).ToString(@"hh\:mm\:ss");