加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何比较今天的给定日期

发布时间:2020-12-15 04:29:15 所属栏目:百科 来源:网络整理
导读:我想比较一个给定的日期到今天,这里是条件:如果提供的日期大于等于6个月前从今天返回true否返回false 码: string strDate = tbDate.Text; //2015-03-29if (DateTime.Now.AddMonths(-6) == DateTime.Parse(strDate)) //if given date is equal to exactly 6
我想比较一个给定的日期到今天,这里是条件:如果提供的日期大于等于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,这不太可能是你解析的日期/时间.对于这篇文章的其余部分,我假设你解析的值真的是一个日期,所以最后一个日期时间是午夜的时间. (当然,在我非常偏见的观点,最好使用 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等) – 否则您可以在评估之间找到更改.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读