【问题标题】:Get Number of Occurrences Based on Date Range and Set Days of Week根据日期范围获取发生次数并设置星期几
【发布时间】:2017-05-09 13:48:14
【问题描述】:

我正在尝试根据以下已知参数计算将发生的事件总数

  1. 开始日期
  2. 结束日期
  3. 星期几
  4. 周频率(每周、每 2 周等)

例如,基于以下示例数据:

  1. 2017 年 5 月 1 日
  2. 2017 年 5 月 31 日
  3. 1,4(周日、周三)
  4. 每 2 周

我必须计算出这个事件会运行四次(5/7、5/10、5/21、5/24)

下面是我设置的骨架。我完全不知道如何根据已经过去的周数在循环中增加当前日期。

<cfset local.totalRuns = 0 />

<cfset local.startDate = '2017-05-01' />
<cfset local.endDate = '2017-05-31' />
<cfset local.totalDays = DateDiff("d", local.startDate, local.endDate) />

<cfset local.daysPerWeek = '1,4' />
<cfset local.recurrence = 2 />

<cfset local.currentLoop = 0 />
<cfset local.weeksToCount = local.recurrence * 2 />

<!--- Loop a day at a time --->
<cfloop from="#local.startDate#" to="#local.endDate#" index="local.thisDay" step="#createTimespan(1, 0, 0, 0)#">

    <cfset local.currentDate = local.thisDay />

    <!--- Loop over each allowed day of the current week and determine actual date ---> 
    <cfloop list="#local.daysPerWeek#" index="local.currentDay">


        <!--- if current date does not exceed the end date add increment (this current is incorrect) --->
        <cfif DateDiff("d", local.currentDate, local.endDate) LTE 0>
            <cfset local.totalRuns++ />
        </cfif>
    </cfloop>

    <cfset local.currentLoop++ />
</cfloop>

【问题讨论】:

  • local.totalRuns 和 local.currentLoop 最后得到什么值?
  • 我非常喜欢使用日期维度表进行日期范围检查。我还认为这里的诀窍是修复事件实际发生的时间。除非我有什么误解,如果偶数每两周在周日运行一次,我认为如果将 startDate 设置为 5/1 和 5/8,这段代码会返回不同的结果。
  • Shawn - 你说得对,2 周有点不清楚。本周开始 1 周,下周开始 2 周,之后每 2 周开始。这是最初的一个有点偏离。
  • techLove - local.totalRuns 将是我返回调用脚本的总次数
  • 同意日历表。他们通常可以大大简化这类任务。 RE:如果您将 startDate 设置为 5/1 与 5/8,此代码将返回不同的结果 是的,只是我的 2 美分,但.. 不确定我是否同意预期的结果。我本来希望活动在第一个星期日或星期三开始,即 5/3 而不是 5/7,但这可能是特定于应用程序的规则。

标签: date coldfusion iteration


【解决方案1】:

这是一个格式化的评论。它显示了我将采取的方法。

set the recurrence count to 0

start looping through the list of valid days of the week (1,4) in this case

set the control date to the start date.

do something to set the control date to the earliest 
date that matches the day of the week in this loop.  

if the control date is greater than the end date, break out of the loop.
otherwise

add 1 to the recurrence count

set up a while loop that adds the specified number of weeks 
to the control date, and repeats the check I just described

end looping through the list of valid days of the week (1,4) in this case

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    • 2012-05-23
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多