Compare Date Months

Hi Experts, I hope someone can suggest an input.
I have 2 date variable months; date_month1 = “APRIL” & date_month2 = “March”

Need to make a condition where month2 variables is within 3 months before or after the month1 variable.
In above case month2 is within month1 - 3 months (April, March February), so its true. However if month2 is August then it is outside 3 months after window, so it should be false.

Hope problem statement is clear so any suggestions will be highly appreciated.

If both variables are already dateTime type you can use this condition:
if : date_month2<= date_month1.addMonths(3)

Hi,

Can you try the following?

m1 =DateTime.ParseExact(date_month1,"MMMM",System.Globalization.CultureInfo.InvariantCulture).Month

m2 = DateTime.ParseExact(date_month2,"MMMM",System.Globalization.CultureInfo.InvariantCulture).Month

Then

(m2 > m1-3 AndAlso m2<m1+3) OrElse (m1<3 AndAlso m2>12+m1-3) OrElse  (m1>10 AndAlso m2<(12-m1)+3)

Main.xaml (6.7 KB)

Regards,

1 Like

thank you @Yoichi, would like to understand the condition (m1<3 AndAlso m2>12+m1-3) OrElse (m1>10 AndAlso m2<(12-m1)+3).
why are we comparing m1 and m2 with 3/12/10 as these are fixed numbers?

Hi,

If target month is March, it easily returns true when input is 3(March)±2 : between 1 and 5 (Jan (1), Feb (2) , Mar (3), Apr (4), May (5))

However If target month is February, it should return True when (Dec (12), Jan (1), Feb (2) , Mar (3), Apr (4) ) and this means we cannot express it as simple range. So, we should consider in case of Jan,Feb,Nov,Dec : this is reason why we should use condition regarding 3 or 10.

image

FYI, as another approach, the following expression will also work in condition of IF.

Enumerable.Range(-2,5).Select(Function(i) DateTime.ParseExact(date_month1,"MMMM",System.Globalization.CultureInfo.InvariantCulture).AddMonths(i).Month).Contains(DateTime.ParseExact(date_month2,"MMMM",System.Globalization.CultureInfo.InvariantCulture).Month)

Regards.

1 Like

Thank you @Yoichi for quick response, it worked.

Thank you @Anas_Pv , appreciate your reply. There are additional number of dates need to be compared so I will consider this option too.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.