Click here to Skip to main content
15,909,466 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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 19:40pm

C#
//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);
 
Share this answer
 
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:
C#
NbMonths= ( retdt.year - reqdt.year ) * 12 + ( retdt.month - reqdt.month )
if ( retdt.day < reqdt.day ) {
  NbMonths--
}
 
Share this answer
 
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: [^]
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900