开发者

Counting the number of days then update it to record ASP.NET C#

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 'dateb开发者_运维百科orrowed' 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!!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜