Calculating Timespan in C# and storing result in MSSQL

Viewed 78

I am trying to calculate the timespan between to sql datetime fields, Bdc_TimeIn (datetime) and Bdc_TimeOut. I need to store the timespan in a third field called Bdc_TimeElapsed which is currently of Data Type time.

I have tried TimeSpan telapsed = Bdc_TimeOut.Subtract(Bdc_TimeIn); but I get the error:

CS1061 'DateTime?' does not contain a definition for 'Subtract' and no accessible extension method 'Subtract' accepting a first argument of type 'DateTime?' could be found (are you missing a using directive or an assembly reference?)

  1. How can I calculate the Timespan between Bdc_TimeIn and Bdc_TimeOut
  2. How can I store the result in my MSSql Database.

Thanks for any help...Very new to this type of data manipulation.

1 Answers

Use the Value property:

// Example values.
DateTime? Bdc_TimeOut = DateTime.Now;
DateTime? Bdc_TimeIn = DateTime.Today;

TimeSpan telapsed = Bdc_TimeOut.Value.Subtract(Bdc_TimeIn.Value);

The timespan could be stored as a long:

long elapsed = telapsed.Ticks;
Related