【问题标题】:How do I find next and previous months across the change of year如何在一年的变化中找到下个月和上个月
【发布时间】:2017-02-10 23:00:26
【问题描述】:

我有两个文本框(开始日期,结束日期)。 如果 startdate 和 enddate 值介于 startDate 月份的任何一个月的 21 日和下个月的 20 日之间,我可以做任何其他事情。

例如,

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

startdate(25/jan/2017) 和 enddate(21/feb/2017):无法执行逻辑

我为此使用了一些逻辑,

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))
            {
            }

但它不适用于 startdate(12 月)和 endDate(1 月),因为 ((startDate2.Day &lt;= 20 &amp;&amp; endDate2.Day &gt;= 21 &amp;&amp; emonth == smonth - 1)) 任何人都可以帮助我正确的逻辑吗?

【问题讨论】:

  • 应该例如允许从同月的 8 日到 15 日吗?

标签: c# asp.net


【解决方案1】:

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

emonth == smonth -1

这意味着如果将 12 月与 1 月进行比较,它就无法工作

1 == 12-1 => false

不提供任何完整的解决方案,但想帮助你一点一点理解;)

【讨论】:

  • 是的,你是对的。如果它是从(1 月 21 日到 12 月 20 日)而不是从(12 月 21 日到 1 月 20 日),则上面的代码运行良好
【解决方案2】:

假设 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);

【讨论】:

  • 感谢您的回答,它正在工作。但不适用于 2016 年,仅适用于(2016 年 12 月,2017 年 1 月至 17 月)
  • 这个答案与年份无关。你能告诉我在哪个开始和结束日期它没有达到你想要的效果吗?
猜你喜欢
  • 1970-01-01
  • 2022-11-27
  • 1970-01-01
  • 2019-04-10
  • 2022-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多