RSS

find the diffrence between 2 DateTimes in C# (DateDiff for you T-SQL Buffs)

09 Mar

SO many times you need to get the amount of time between 2 dates or you need to validate that the range between DateTimes is not within or beyond a certain amount of seconds,minutes,hours,days,months, and/or years. In T-SQL you get this info with the DateDiff function in c# we don’t have a function persay but the datetime type does have a method you can use to get it here is an example of the subtraction version.

//these are date time controls that we cast the values as date time
                et = (DateTime)EarliestCallDate.SelectedDate;
                lt = (DateTime)LatestCallDate.DbSelectedDate;
// now lets get the diffrence in days
            if (et > lt)
            {
                error.Text = "Earliest Call Date Cannot Be Less Than Latest Call Date.";
                return;
            }
            else if (lt.Subtract(et).Days > 1) // right here it is
            {
                error.Text = "Earliest Date and Latest Date must be in the same day";
            }

As you can see it is pretty simple the Return Type of lt.Subtract(et).Days is TimeSpan.Days. Well hopefully this helps someone until next time I post don’t let your code have a meltdown.

Advertisements
 
Leave a comment

Posted by on March 9, 2012 in C#, C# for Beginners

 

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: