Madhan
Madhan

Reputation: 260

compare the date below current month c#

How to check the given date is less then or equal to the current month. i.e., any datetime less then or equal to current month should return true.

Upvotes: 2

Views: 4156

Answers (3)

Unmesh Kondolikar
Unmesh Kondolikar

Reputation: 9312

You can simply compare the Year and Month values if the two DateTime values -

DateTime d1, d2;
...
d1.Year <= d2.Year && d1.Month < d2.Month;

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1063619

Two options;

1: find month start and compare:

var monthStart = new DateTime(when.Year, when.Month, 1);
if(someDate < monthStart) {...}

2: compare the month and year

if(someDate.Year < when.Year || (someDate.Year == when.Year &&
                         someDate.Month < when.Month)) {...}

either would be suitable for an extension method on DateTime

Upvotes: 5

jason
jason

Reputation: 241711

As an extension method:

public static bool IsBeforeStartOfCurrentMonth(this DateTime date) {
    DateTime now = DateTime.Now;
    DateTime startOfCurrentMonth = new DateTime(now.Year, now.Month, 1);
    return date < startOfCurrentMonth;
}

Usage:

DateTime date = // some DateTime
if(date.IsBeforeStartOfCurrentMonth()) {
    // do something
}

Upvotes: 6

Related Questions