如何在一年中的变化中找到下个月和前几个月

时间:2017-02-10 14:05:29

标签: c# asp.net

我有两个文本框(startdate,enddate)。 如果startdate和startdate值在startDate月份的任何月份的21日和下个月的20日之间,则表示我可以做任何其他事情。

例如,

startdate(25 / jan / 2017)和enddate(20 / feb / 2017):可以做任何逻辑

startdate(25 / jan / 2017)和enddate(21 / feb / 2017):不可能做逻辑

我使用了一些逻辑,

property

但它不能用于startdate(12月份)和endDate(1月份月份),因为if ((startDate2.Day >= 21 && endDate2.Day >= 21 && emonth == smonth) || (startDate2.Day >= 21 && endDate2.Day <= 20 && emonth == smonth + 1) || (startDate2.Day <= 20 && endDate2.Day <= 20 && emonth == smonth) || (startDate2.Day <= 20 && endDate2.Day >= 21 && emonth == smonth - 1)) { } 有人可以用正确的逻辑来帮助我吗?

2 个答案:

答案 0 :(得分:0)

可能是因为您期望end month正好比起始月少一个

emonth == smonth -1

如果比较12月到1月,这意味着它无法正常工作

1 == 12-1 => false

不提供任何完整的解决方案,但希望一点一点地帮助您理解;)

答案 1 :(得分:0)

假设smonthemonthint并定义从112的月份,您可以在月份上使用模数:

if ((startDate2.Day >= 21 && endDate2.Day >= 21 && emonth == smonth) 
     || (startDate2.Day >= 21 && endDate2.Day <= 20 && emonth == ((smonth + 2)%12)-1)         
     || (startDate2.Day <= 20 && endDate2.Day <= 20 && emonth == smonth) 
     || (startDate2.Day <= 20 && endDate2.Day >= 21 && ((emonth+2)%12)-1 == smonth))

但请注意,这仍然允许例如2015年12月23日至2017年1月12日。

为避免这种情况,您还应该比较年份或实施将endDate-startDate限制为31天的其他条件:

endDate <= startDate.AddDays(31);
相关问题