Click here to Skip to main content
14,426,057 members
Rate this:
Please Sign up or sign in to vote.
See more:
Good day everyone please i want to calculate months differences between two date time picker. And i want it to give me an error if it more than one year. the code here is for if the dates choosen has not expired

What I have tried:

<pre>DateTime reqdt = dtrequest.Value.Date;
DateTime retdt = dtreturn.Value.Date;

TimeSpan ts = retdt - reqdt;
int days = ts.Days;
if (days <= 0)
{
MessageBox.Show("Date Expired");
}
else
{
MessageBox.Show("better");

lbldiff.Text = days.ToString() + "Days";
Posted
Updated 24-May-19 20:40pm
Rate this:
Please Sign up or sign in to vote.

Solution 3

//The trick here is to use the AddYears method
DateTime firstDate = DateTime.Now;
DateTime secondDate= firstDate.AddDays(367);
DateTime expiryDate = firstDate.AddYears(1);
string msg = secondDate > expiryDate ? "Expired" : "Not Expired";
Console.WriteLine(msg);
   
Rate this:
Please Sign up or sign in to vote.

Solution 1

Quote:
i want to calculate months differences between two date time

You basically have 2 solutions:
- Either you say that a month is roughly 31.5 days and use the number of days for the calculation.
- Either you do the calculation yourself by handling years, months and days of both dates.
it will look like:
NbMonths= ( retdt.year - reqdt.year ) * 12 + ( retdt.month - reqdt.month )
if ( retdt.day < reqdt.day ) {
  NbMonths--
}
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

If you need a more accurate calculation, that takes internationalization (Culture/Calendar) into account, CodeProject has an excellent article/code-library by Jani Giannoudis: [^]. This is being developed on GitHub now, and updated for .NET Core, Mono, Xamarin and UWP.

You can examine the (complex) code in the 'DateDiff class to see how total months are calculated.

Another full featured C# library for Date/Time calculations is Jon Skeet's 'NodaTime: [^] ... on GitHub: [^]
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100