如何比较今天的给定日期

时间:2015-09-29 16:35:13

标签: c# datetime

我想将给定日期与今天进行比较,以下是条件:如果提供日期大于或等于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个月是另一个条件。

2 个答案:

答案 0 :(得分:12)

你的第一个问题是你使用的是DateTime.Now而不是DateTime.Today - 所以减去6个月会给你另一个DateTime一个特定的时间,这是不太可能的完全您解析的日期/时间。对于这篇文章的其余部分,我假设您解析的值实际上是一个日期,因此最终会得到一个DateTime,其中包含一个星期几的午夜时间。 (当然,在我非常偏见的观点中,最好使用a library which supports "date" as a first class concept ...)

下一个问题是,您假设从今天开始减去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
{
    // ...
}

或者 - 和不等同于

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等)一次 - 否则您会发现评估之间会发生变化。

答案 1 :(得分:1)

试试这个

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.
}

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