如何比较给定的日期和今天

本文关键字:日期 今天 何比较 比较 | 更新日期: 2023-09-27 18:15:20

我想比较给定的日期和今天,条件如下:如果提供的日期比今天早6个月,则返回true,否则返回false

代码:

string strDate = tbDate.Text; //2015-03-29
if (DateTime.Now.AddMonths(-6) == DateTime.Parse(strDate)) //if given date is equal to exactly 6 months past from today (change == to > if date has to be less 6 months)
{
    lblResult.Text = "true"; //this doesn't work with the entered date above.
}
else //otherwise give me the date which will be 6 months from a given date.
{
    DateTime dt2 = Convert.ToDateTime(strDate);
    lblResult.Text = "6 Months from given date is: " + dt2.AddMonths(6); //this works fine
}
  • 如果6个月或大于6个月是我想要的
  • 如果少于6个月是另一种情况。

如何比较给定的日期和今天

你的第一个问题是你使用DateTime.Now而不是DateTime.Today -所以减去6个月将给你另一个DateTime与一天中的特定时间,这是非常不可能的完全你已经解析的日期/时间。对于本文的其余部分,我假设您解析的值实际上是一个日期,因此您最终得到一个DateTime,其时间为午夜。(当然,在我个人看来,最好使用一个支持"date"作为第一类概念的库…)

下一个问题是,你假设从今天减去6个月并将其与固定日期进行比较,相当于在固定日期上增加6个月并将其与今天进行比较。它们不是同一种运算——日历运算不是这样的。你应该找出你想要的工作方式,并保持一致。例如:

DateTime start = DateTime.Parse(tbDate.Text);
DateTime end = start.AddMonths(6);
DateTime today = DateTime.Today;
if (end >= today)
{
    // Today is 6 months or more from the start date
}
else
{
    // ...
}

或者-和not等价:

DateTime target = DateTime.Parse(tbDate.Text);
DateTime today = DateTime.Today;
DateTime sixMonthsAgo = today.AddMonths(-6);
if (sixMonthsAgo >= target)
{
    // Six months ago today was the target date or later
}
else
{
    // ...
}

请注意,您应该只计算DateTime.Today(或DateTime.Now等)一次每组计算-否则您会发现它在计算之间发生变化。

试试这个

DateTime s = Convert.ToDateTime(tbDate.Text);
s = s.Date;
if (DateTime.Today.AddMonths(-6) == s) //if given date is equal to exactly 6 months past from today (change == to > if date has to be less 6 months)
{
lblResult.Text = "true"; //this doesn't work with the entered date above.
}

根据您的需要替换为>=或<=