Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compare month-year with DateParse

Tags:

c#

datetime

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

I know how to do it only with single month or year, like

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

or

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

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

EDIT

What I have to do is, for example, to check if 10-2011 (DateTime.Now.Month-DateTime.Now.Year) is between 01-2011 and 04-2012...

like image 545
markzzz Avatar asked Oct 24 '11 09:10

markzzz


People also ask

Can you compare two dates JavaScript?

In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.

How do I compare two dates in typescript?

Call the getTime() method on each date to get a timestamp. Compare the timestamp of the dates. If a date's timestamp is greater than another's, then that date comes after.


2 Answers

If the years are the same, compare the months, if the years are not the same, your year must be smaller 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 is in a certain 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, i.e. 
    // exclusive lower bound, change the >= to >.
    // if you want yourDate to be in the range 01/01/2011 - 31/03/2012, i.e.
    // exclusive upper bound, change the <= to <.
}
like image 53
Daniel Hilgarth Avatar answered Oct 20 '22 12:10

Daniel Hilgarth


var date1 = new DateTime(year1, month1, 1);
var date2 = new DateTime(year2, month2, 1);

if(date1 < date2)...
like image 28
Luis Carlos Pignataro Avatar answered Oct 20 '22 12:10

Luis Carlos Pignataro