使用Coldfusion,如何确定在工作时间(另一个时间跨度)内是否发生给定的时间跨度?

时间:2010-02-09 18:22:07

标签: coldfusion

鉴于某项业务在上午8点至下午5点开放,验证给定时间跨度是否在该范围内的最佳方法是什么?日期并不重要,只需要确认整个要求的时间范围都在营业时间内。

以下是我必须开始的示例数据。 (我在这里使用cfscript只是为了简洁)

<cfscript>
    // array of given timeslots to test
    timeslots = arrayNew(1);

    // 1st appointment, entirely within normal business hours
    appointment = structNew();
    appointment.begin = "10:00 AM";
    appointment.end = "2:00 PM";

    arrayAppend(timeslots, appointment);

    // 2nd appointment, outside of normal business hours
    appointment = structNew();
    appointment.begin = "7:00 PM";
    appointment.end = "9:00 PM";

    arrayAppend(timeslots, appointment);

    // 3rd appointment, kind of tricky, partly within business hours, still should fail
    appointment = structNew();
    appointment.begin = "3:00 PM";
    appointment.end = "6:00 PM";

    arrayAppend(timeslots, appointment);

    </cfscript>

现在,我将遍历该数组,在每个结构上运行验证函数。例如,它可能看起来像这样:

<cfoutput>
<cfloop array="#timeslots#" index="i">
    <!--- Should return 'true' or 'false' for each item --->
    #myValidator(i.begin, i.end)#<br />
</cfloop>
</cfoutput>

...回到真正的问题,......我如何使用Coldfusion将这些时间与给定的营业时间进行比较?

<cfscript>
// if input data is outside of the internal time range, return false, otherwise true
function myValidator(begin, end) {
    var businessStart = "8:00 AM";
    var businessEnd = "5:00 PM";
    var result = false;

    // what kind of tests do I put here to compare the times?
}
</cfscript>

更新:我的解决方案 - 根据Ben Doom和kevink的反馈,从上面重写myValidator。

// checks if any scheduled events fall outside business hours
function duringBusinessHours(startTime, endTime) {
    var result = true;
    var busStart = 800;
    var busEnd = 1700;
    var startNum = 0;
    var endNum = 0;

    // convert time string into a simple number:
    // "7:00 AM" -> 700 | "3:00 PM" -> 1500
    startNum = timeFormat(arguments.startTime, "Hmm");
    endNum = timeFormat(arguments.endTime, "Hmm");

    // start time must be smaller than end time
    if (startNum GTE endNum) {
       result = false;

    // If start time is outside of business hours, fail
    } else if (startNum LT busStart OR startNum GT busEnd) {
       result = false;  

    // If end time is outside of business hours, fail
    } else if (endNum LT busStart OR endNum GT busEnd) {
       result = false;
    }
    return result;
}

3 个答案:

答案 0 :(得分:1)

我个人会使用CreateDateTime创建两个具有相同m / d / y值的日期对象并进行比较,因为CF可以正确地执行此操作。

答案 1 :(得分:1)

如果您不关心使用24小时制的时间,请将所有内容视为一个简单的数字,并使用大于,小于......

 <cfif arguments.startime LT bizStart OR arguments.endtime GT bizEnd>
   <cfreturn false>
 <cfelse>
   <cfreturn true>
 </cfif>

答案 2 :(得分:0)

您肯定希望使用CreateDateTime创建日期/时间对象,然后比较日期/时间框架。如果从网页中将输入作为字符串输入,则可以使用ParseDateTime将表示有效日期/时间格式的字符串转换为日期/时间对象。