【问题标题】:DateDiff Calculation Issue - MonthsDateDiff 计算问题 - 月
【发布时间】:2012-11-27 10:58:40
【问题描述】:

请任何人为我阐明这一点,并可能提出解决方案。

我正在创建一个自定义日历,用于安排活动。

在构造函数中,我传入 2 个日期(startDateendDate

表单有一个 FlowLayoutPanel,然后填充了月份的用户控件。

我遇到的问题是,当我使用以下日期执行 DateDiff(DateInterval.Month, startDate, endDate) 时:startDate = 22/11/2012, endDate = 28/02/2013 结果是 3.

但实际上,在日历上,我需要显示 4 个月 - 11 月、12 月、1 月和 2 月。

尽管如此,startDate = 12/11/2012, endDate = 01/03/2012

的逻辑工作正常

【问题讨论】:

  • 嗯,间隔刚刚超过 3 个月,所以大概是 3 个月零 6 天(左右)。您获得了整月的正确值,但似乎还希望将额外的天数计为另一个月。
  • 但即使我修正了日期,即设置 startDate = 01/11/2012 并设置 endDate = 31/02/2013 我仍然没有得到 4 个月。
  • 对不起,我的意思是 endDate = 28/02/2013

标签: vb.net winforms datediff


【解决方案1】:

来自 DateDiff 上的 MSDN 文档

如果 Interval 设置为 DateInterval.Year,则返回值为 纯粹从 Date1 和 Date2 的年份部分计算。相似地, DateInterval.Month 的返回值纯粹从 参数的年份和月份部分,以及 DateInterval.Quarter 从包含两个日期的季度。

例如,当比较以下的 12 月 31 日和 1 月 1 日时 年,DateDiff 为 DateInterval.Year、DateInterval.Quarter 返回 1, 或 DateInterval.Month,即使最多只过去了一天。

这意味着计算不考虑剩余的“天”,

也许您应该构建您的自定义日历,而不是使用 DateDiff 来查找所涉及的月份。
相反,您应该使用这样的伪代码:

 Dim curMonth = startDate.Month
 Dim curYear = startDate.Year
 while curMonth <= endDate.Month andalso curYear <= endDate.Year
     AddCalendar(curMonth, curYear)
     curMonth = curMonth + 1
     if curMonth > 12 then 
         curMonth = 1
         curYear = curYear + 1
     end if
 end while

【讨论】:

    【解决方案2】:

    如果我理解正确,即使日期之间的实际差异小于 3 个月,您也会希望显示 4 个月。一种解决方案是这样的:

    Dim startDate = #11/22/2012# 'Nov 22nd
    Dim endDate = #2/2/2013# 'Feb 2nd
    
    Dim startMonth = new DateTime (startDate.Year, startDate.Month, 1)
    Dim endMonth = new DateTime (endDate.Year, endDate.Month, 1).AddMonths (1)
    Dim diff = DateDiff (DateInterval.Month, startMonth, endMonth)
    

    【讨论】:

    • 我希望日历显示日期范围内的所有月份,这是正确的。但是,我不想显示额外的、不需要的月份,而且我担心您的解决方案可能会在 dateDiff 现在正常工作的情况下执行此操作。
    • 我的解决方案包括开始月份、结束月份以及中间的所有月份(仅此而已)。
    猜你喜欢
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多