开发者

compare the date below current month c#

How to check the given date is 开发者_如何学Cless then or equal to the current month. i.e., any datetime less then or equal to current month should return true.


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
}


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


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜