我想比较一个给定的日期到今天,这里是条件:如果提供的日期大于等于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等) – 否则您可以在评估之间找到更改.