0

So I have a gridview with 'dateborrowed' and 'datereturned'. What I want is that the program will count for the number of days in between the 'dateborrowed' and 'datereturned' like for example 'dateborrowed' = April 1, 2011 - 'datereturned' = April 30, 2011 = 29 days in between. Also I want the value to automatically insert to a record 'daysibetween'. So how can I do that?

Help would be much appreciated. Thanks in advance!!

Loupi
  • 1,102
  • 4
  • 25
  • 42
  • what is `daysibetween`? A database table? – Abe Miessler May 16 '11 at 02:06
  • no its another column. I have a database 'lendbooks' with column 'dateborrowed', 'datereturned' and 'daysinbetween'. I want to insert the number of days value in between 'dateborrowed' and 'datereturned' to 'dayseinbetween' – Loupi May 16 '11 at 02:25
  • 1
    possible duplicate of [C#: Calculate difference between two dates (number of days)?](http://stackoverflow.com/questions/1607336/c-calculate-difference-between-two-dates-number-of-days) – Ranhiru Jude Cooray May 16 '11 at 03:25

2 Answers2

4

There are several ways you can accomplish this

A very much neat way

(a - b).TotalDays

taken from Calculate difference between two dates (number of days)?

DateTime d1=DateTime.MinValue;
DateTime d2=DateTime.MaxValue;
TimeSpan span=d2-d1;
Console.WriteLine( "There're {0} days between {1} and {2}" , span.TotalDays, d1.ToString(), d2.ToString() );

OR

private int GetDaysBetweenDates(DateTime firstDate, DateTime secondDate)
{
   return secondDate.Subtract(firstDate).Days;
}

They were all taken from this thread in MSDN.

Once calculated, adding it to the database is an UPDATE query.

Community
  • 1
  • 1
Ranhiru Jude Cooray
  • 19,542
  • 20
  • 83
  • 128
1

I know this is not the answer you might be looking for, but according to good database design, you should not really be storing the calculated DaysInBetween in your table. You can calculate that value any time you need it by using a variety of methods (including those in Rahhiru's answer).

If you are using SQL Server, you can use the DateDiff function to calculate the number of days in your Select statement: DateDiff(day, dateBorrowed, dateReturned) as DaysInBetween.

For that matter, you could use a computed column in your table to make this look like an actual column even though it would be calculated on the fly whenever you retrieved it.

patmortech
  • 10,139
  • 5
  • 38
  • 50