Question

I want to calculate the time span between 2 times which I saved in a database. So literally I want to know the length of time between the 2 values.

14:10:20 - 10:05:15 = 02:05:05

So the result would be 02:05:05.

How would I be able to achieve this using C#?

14:10:20 is the format I saved it in in my database.

Was it helpful?

Solution

Read the two time values into TimeSpan variables, then perform a .Subtract() on the bigger TimeSpan variable to get the TimeSpan result.

E.g. TimeSpan difference = t1.Subtract(t2);.

OTHER TIPS

Your first step will be to get the timevalues stored in your database into .NET DateTime structs.

If you stored them as SQL-DateTime values in the database you can get them directly as DateTime. It would look something like this:

SQLCommand getTimeCommand = new SQLCommand("SELECT time FROM table", dbConnection);
SQLDataReader myReader = getTimeCommand.ExecuteReader();
while (myReader.Read())
{
    DateTime time = myReader.GetDateTime(0);
}
myReader.Close();

Your implementation might differ, refer to the ADO.NET documentation in the MSDN library.

If you already got a string representing the time you can parse the string into a DateTime using the static methods

DateTime.Parse 

or

DateTime.ParseExact

In your case you might need to use ParseExact, which can pe provided with a format-string defining how to read the string. Examples should be found in the MSDN library.

Durations in .NET are stored inside a TimeSpan struct. Getting the elapsed time between to datetimes is easy:

DateTime time1, time2; //filled with your timevalues from the db
TimeSpan elapsed = d2 - d1;

elapsed now contains the timespan between the two DateTimes. There are several members for the struct to access the TimeSpan. Look into the MSDN-Library to find the ones you need.

DateTime objects support the "-" operator so you can just read your times into such objects and subtract them. To test, check this out:

DateTime then = DateTime.Now;
Thread.Sleep(500);
DateTime now = DateTime.Now;
TimeSpan time = now - then;
MessageBox.Show(time.ToString());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top