Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Month difference between 2 dates

Tags:

c#

datetime

I am trying to calculate MONTH difference between one date column and today. Do we have any method in csharp like monthdiff or datediff to achieve this functionlaity? Issue with my code is if submission date year is different then it breaks.

bool isDateAccepted = ((SubmissionDate.Month - DateTime.Now.Month) < 6)
like image 549
Kurkula Avatar asked Nov 20 '25 06:11

Kurkula


2 Answers

You could always add 6 months to the submission date, and compare it to the current date.

bool isDateAccepted = (submissionDate.AddMonths(6) > DateTime.Now);
like image 143
Velox Avatar answered Nov 22 '25 21:11

Velox


Don't directly compare the Month variables, as it will break when the month number "wraps" as you have noticed.

Instead, subtract the DateTime objects to get a TimeSpan then use that TotalDays property:

bool isDateAccepted = ((SubmissionDate - DateTime.Now).TotalDays < 6 * 30)

TimeSpan doesn't consider Months, so you'll have to define an average number of days in order to check the number for months passed.

like image 45
BradleyDotNET Avatar answered Nov 22 '25 21:11

BradleyDotNET



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!