如何将月份与DateParse进行比较

mar*_*zzz 7 c# datetime

我必须检查日期(月 - 月)是否低于实际日期.

我知道如何只用一个月或一年来做,比如

DateTime.Parse(o.MyDate).Month <= DateTime.Now.Month
Run Code Online (Sandbox Code Playgroud)

要么

DateTime.Parse(o.MyDate).Year <= DateTime.Now.Year
Run Code Online (Sandbox Code Playgroud)

但如果月份比现在减去,我怎么能直接检查.month-now.year?

编辑

我要做的是,例如,检查10-2011(DateTime.Now.Month-DateTime.Now.Year)是否在01-2011和04-2012之间......

xan*_*tos 6

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)
Run Code Online (Sandbox Code Playgroud)

第二种选择:

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;
Run Code Online (Sandbox Code Playgroud)

第三种选择(或许更多"旧学校")

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;
Run Code Online (Sandbox Code Playgroud)


Dan*_*rth 5

如果年份相同,则比较月份,如果年份不同,则您的年份必须小于现在:

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

更新:

要检查是否yourDate在某个时间范围内,请使用以下命令:

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 <.
}
Run Code Online (Sandbox Code Playgroud)