Question

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.

Was it helpful?

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");

OTHER TIPS

You can use this logic (replacing the DateTime.Nows with your values:

        var datetimediff = new DateTime((DateTime.Now.AddMinutes(1) -    DateTime.Now).Ticks);
        var TimeTook = datetimediff.ToString("HH:mm:ss");

Try this

Convert.ToDateTime(reader.GetDateTimeNullable("COMPLETED_DATE") - reader.GetDateTime("REQUEST_DATE")).ToString("HH:mm:ss");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top