如何将月份与DateParse进行比较

时间:2011-10-24 09:31:11

标签: c# datetime

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

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

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

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

但是如何直接检查月份是否比现在还要晚。现在是什么时候?

修改

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

5 个答案:

答案 0 :(得分: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)

第二个选项:

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;

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

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;

答案 1 :(得分: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.
}

更新:

要检查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 <.
}

答案 2 :(得分:3)

DateTime dateCheck = DateTime.Parse(o.MyDate);
bool result = ((Now.Month - dateCheck.Month) + 12 * (Now.Year - dateCheck.Year)) > 0

答案 3 :(得分:0)

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

如果结果是&lt; 0然后date1&lt; DATE2
如果结果为0则date1 == date2
如果结果是> 0 date1&gt; DATE2

答案 4 :(得分:0)

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

if(date1 < date2)...