How to compare month-year with DateParse

I have to check if there is a date (month-year) minus the actual date.

I know how to do this with only one month or year, for example

DateTime.Parse(o.MyDate).Month <= DateTime.Now.Month 

or

 DateTime.Parse(o.MyDate).Year <= DateTime.Now.Year 

but how can I check if month-year is minus than now.month-now.year?

EDIT

What I need to do, for example, check if there will be 10-2011 (DateTime.Now.Month-DateTime.Now.Year) from 01-2011 to 04-2012 ...

+6
source share
4 answers

If the years are the same, compare the months, if the years do not match, your year should be less than now:

 var yourDate = ...; if((yourDate.Year == DateTime.Now.Year && yourDate.Month < DateTime.Now.Month) || yourDate.Year < DateTime.Now.Year) { // yourDate is smaller than todays month. } 

UPDATE:

To check if yourDate in a specific time range, use this:

 var yourDate = ...; var lowerBoundYear = 2011; var lowerBoundMonth = 1; var upperBoundYear = 2012; var upperBoundMonth = 4; if(((yourDate.Year == lowerBoundYear && yourDate.Month >= lowerBoundMonth) || yourDate.Year > lowerBoundYear ) && ((yourDate.Year == upperBoundYear && yourDate.Month <= upperBoundMonth) || yourDate.Year < lowerBoundYear )) { // yourDate is in the time range 01/01/2011 - 30/04/2012 // if you want yourDate to be in the range 01/02/2011 - 30/04/2012, ie // exclusive lower bound, change the >= to >. // if you want yourDate to be in the range 01/01/2011 - 31/03/2012, ie // exclusive upper bound, change the <= to <. } 
+5
source
 var date = DateTime.Parse(o.MyDate); var year = date.Year; // We don't even want to know what could happen at 31 Dec 23.59.59 :-) var currentTime = DateTime.Now; var currentYear = currentTime.Year; bool result = year < currentYear || (year == currentYear && date.Month <= currentTime.Month) 

Second option:

 var date = DateTime.Parse(o.MyDate).Date; // We round to the day date = date.AddDays(-date.Day); // and we remove the day var currentDate = DateTime.Now.Date; currentDate = currentDate.AddDays(-currentDate.Day); bool result = date <= currentDate; 

The third option (perhaps more "old school")

 var date = DateTime.Parse(o.MyDate); var currentTime = DateTime.Now; // Each year can be subdivided in 12 parts (the months) bool result = date.Year * 12 + date.Month <= currentTime.Year * 12 + currentTime.Month; 
+5
source
 DateTime dateCheck = DateTime.Parse(o.MyDate); bool result = ((Now.Month - dateCheck.Month) + 12 * (Now.Year - dateCheck.Year)) > 0 
+3
source
 Date date1 = new Date(2011, 1, 1, 0, 0, 0); Date date2 = new Date(2011, 2, 1, 0, 0, 0); int result = DateCompare(date1, date2); 

if the result is <0, then date1 <date2
if the result is 0, then date1 == date2
if the result is> 0, date1> date2

0
source

Source: https://habr.com/ru/post/899949/


All Articles