DurationCalculator를 사용하여 기한 계산

  • 릴리스 버전: Zurich
  • 업데이트 날짜 2025년 07월 31일
  • 소요 시간: 15분
  • DurationCalculator 스크립트 포함을 사용하면 일정에 따라 단순 기간 또는 상대 기간을 기준으로 기한을 계산할 수 있습니다.

    다음 스크립트는 전역 API DurationCalculator 를 사용하여 기한을 계산하는 방법을 보여 줍니다. 스크립트의 첫 번째 부분에서는 setStartDateTime() 메서드를 사용하여 시작 날짜/시간을 설정한 다음 calcDuration() 메서드를 사용하여 지정된 시작 날짜/시간에서 연속 시간(초)의 "x"인 기한을 결정하는 방법을 보여 줍니다. 스크립트의 후반부에서는 DurationCalculator 를 사용하여 일정에 따라 기한을 계산하는 방법을 보여 줍니다. 일정을 사용하면 계산 내에 작업 주의 일만 포함하는 등 향후 시간에 대한 "필터"를 적용할 수 있습니다. 예를 들어 기간 계산에 "평일"(월요일부터 금요일까지만 포함) 일정을 적용하고 시작 날짜/시간이 금요일 오후 5:00인 경우 기간을 2일로 추가하면 기한은 화요일 오후 5:00가 됩니다. 일정을 사용하지 않은 경우 기한은 일요일 오후 5:00입니다. 일정에 대한 자세한 내용은 일정 생성 및 사용을 참조하십시오.

    이 스크립트를 잘라내어 스크립트 백그라운드 페이지에 붙여넣고 있는 그대로 실행할 수 있습니다. 또한 비즈니스 규칙, UI 작업을 작성하기 위한 예시로 사용하거나 서버 측 스크립트를 작성할 수 있는 다른 위치에 사용할 수 있습니다.
    /**
     * Demonstrate the use of DurationCalculator to compute a due date.
     * 
     * You must have a start date and a duration. Then you can compute a
     * due date using the constraints of a schedule.
     */
     
    gs.include('DurationCalculator');
    executeSample();
     
    /**
     * Function to house the sample script.
     */
    function executeSample(){
     
        // First we need a DurationCalculator object.
        var dc = new DurationCalculator();
     
        // --------------- No schedule examples ------------------
     
        // Simple computation of a due date without using a schedule. Seconds
        // are added to the start date continuously to get to a due date.
        var gdt = new GlideDateTime("2012-05-01 00:00:00");
        dc.setStartDateTime(gdt);
        if(!dc.calcDuration(2*24*3600)){ // 2 days
          gs.log("*** Error calculating duration");
          return;
        }
        gs.log("calcDuration no schedule: " + dc.getEndDateTime()); // "2012-05-03 00:00:00" two days later
     
        // Start in the middle of the night (2:00 am) and compute a due date 1 hour in the future
        // Without a schedule this yields 3:00 am.
        var gdt = new GlideDateTime("2012-05-03 02:00:00");
        dc.setStartDateTime(gdt);
        if(!dc.calcDuration(3600)){
          gs.log("*** Error calculating duration");
          return;
         }
        gs.log("Middle of night + 1 hour (no schedule): "+ dc.getEndDateTime()); // No scheduled start date, just add 1 hour
     
     
        // -------------- Add a schedule to the date calculator ---------------------
        addSchedule(dc);
     
        // Start in the middle of the night and compute a due date 1 hour in the future.
        // Since we start at 2:00 am the computation adds the 1 hour from the start
        // of the day, 8:00am to get to 9:00am
        var gdt = new GlideDateTime("2012-05-03 02:00:00");
        dc.setStartDateTime(gdt);
        if(!dc.calcDuration(3600)){
          gs.log("*** Error calculating duration");
          return;
        }
        gs.log("Middle of night + 1 hour (with 8-5 schedule): " + dc.getEndDateTime()); // 9:00 am
     
        // Start in the afternoon and add hours beyond quiting time. Our schedule says the work day
        // ends at 5:00pm, if the duration extends beyond that, we roll over to the next work day.
        // In this example we are adding 4 hours to 3:00pm which gives us 10:00 am the next day.
        var gdt = new GlideDateTime("2012-05-03 15:00:00");
        dc.setStartDateTime(gdt);
    
        if(!dc.calcDuration(4*3600)){ 
          gs.log("*** Error calculating duration");
          return;}
        gs.log("Afternoon + 4 hour (with 8-5 schedule): " + dc.getEndDateTime()); // 10:00 am.
     
        // This is a demo of adding 2 hours repeatedly and examine the result. This
        // is a good way to visualize the result of a due date calculation.
        var gdt = new GlideDateTime("2012-05-03 15:00:00");
        dc.setStartDateTime(gdt); 
        for(var i=2; i<24; i+=1){
          if(!dc.calcDuration(i*3600)){
            gs.log("*** Error calculating duration");
            return;
          }
          gs.log("add "+ i +" hours gives due date: " + dc.getEndDateTime());
        }
     
        // Setting the timezone causes the schedule to be interpreted in the specified timezone.
        // Run the same code as above with different timezone. Note that the 8 to 5 workday is
        // offset by the two hours as specified in our timezone.
        dc.setTimeZone("GMT-2");
        var gdt = new GlideDateTime("2012-05-03 15:00:00");
        dc.setStartDateTime(gdt);
        for(var i=2; i<24; i+=1){
          if(!dc.calcDuration(i*3600)){ 
            gs.log("*** Error calculating duration");
            return;
          }
            gs.log("add "+ i +" hours gives due date (GMT-2): " + dc.getEndDateTime());
        }
    }
     
    /** 
     * Add a specific schedule to the DurationCalculator object.
     *  
     * @param durationCalculator An instance of DurationCalculator
     */
    function addSchedule(durationCalculator){
        // Load the "8-5 weekdays excluding holidays" schedule into our duration calculator.
        var scheduleName = "8-5 weekdays excluding holidays";
        var grSched = new GlideRecord('cmn_schedule');
        grSched.addQuery('name', scheduleName);
        grSched.query();
        if(!grSched.next()){
          gs.log('*** Could not find schedule "'+ scheduleName +'"');
          return;
        }
        durationCalculator.setSchedule(grSched.getUniqueValue(),"GMT");
    }

    DurationCalculator를 사용하여 단순 기간 계산

    단순 지속 기간은 두 날짜 시간 사이의 초 수입니다.

    일정을 사용하지 않으면 간단한 시간 날짜 빼기입니다. 일정을 사용하는 경우 해당 일정을 참조하여 작업 외 시간을 계산에서 제거합니다. 일정 "휴일을 제외한 평일 8-5"를 사용한다고 가정합니다. 이 경우 월요일 정오부터 화요일 정오까지의 작업 시간은 9시간입니다. 단순 지속 시간을 계산하려면 전역 API DurationCalculator 를 초기화하고 calcScheduleDuration() 메서드를 호출합니다.

    이 스크립트는 DurationCalculator 를 사용하여 단순 기간을 계산하는 방법을 보여 줍니다.
    /**
     * Sample script demonstrating use of DurationCalculator to compute simple durations
     * 
     */
     
    gs.include('DurationCalculator');
    executeSample();
     
    /**
     * Function to house the sample script.
     */
    function executeSample(){
     
        // First we need a DurationCalculator object.
        var dc = new DurationCalculator();
     
        // Compute a simple duration without any schedule. The arguments
        // can also be of type GlideDateTime, such as fields from a GlideRecord.
        var dur = dc.calcScheduleDuration("2012-05-01", "2012-05-02");
        gs.log("calcScheduleDuration no schedule: " + dur); // 86400 seconds (24 hours)
     
        // The above sample is useful in limited cases. We almost always want to 
        // use some schedule in a duration computation, let's load a schedule.
        addSchedule(dc);
     
        // Compute a duration using the schedule. The schedule
        // specifies a nine hour work day. The output of this is 32400 seconds, or
        // a nine hour span.
        dur = dc.calcScheduleDuration("2012-05-23 12:00:00","2012-05-24 12:00:00");
        gs.log("calcScheduleDuration with schedule: " + dur); // 32400 seconds (9 hours)
     
        // Compute a duration that spans a weekend and holiday. Even though this
        // spans three days, it only spans 9 work hours based on the schedule.
        dur = dc.calcScheduleDuration("2012-05-25 12:00:00", "2012-05-29 12:00:00");
        gs.log("calcScheduleDuration with schedule spaning holiday: " + dur); // 32400 seconds (9 hours)
     
        // Use the current date time in a calculation. The output of this is
        // dependent on when you run it.
        var now = new Date();
        dur = dc.calcScheduleDuration("2012-05-15", new GlideDateTime());
        gs.log("calcScheduleDuration with schedule to now: " + dur); // Different on every run.
    }
     
    /** 
     * Add a specific schedule to the DurationCalculator object.
     *  
     * @param durationCalculator An instance of DurationCalculator
     */
    function addSchedule(durationCalculator){
        // Load the "8-5 weekdays excluding holidays" schedule into our duration calculator.
        var scheduleName = "8-5 weekdays excluding holidays";
        var grSched = new GlideRecord('cmn_schedule');
        grSched.addQuery('name', scheduleName);
        grSched.query();
        if(!grSched.next()){
            gs.log('*** Could not find schedule "'+ scheduleName +'"');
            return;
        }
        durationCalculator.setSchedule(grSched.getUniqueValue());
    }

    상대 기간 사용

    상대 기간은 차이 계산에서 제거할 하루 중 어느 부분을 결정하기 위해 스크립트를 사용하느냐는 점을 제외하면 단순 기간과 매우 유사합니다.

    이 스크립트는 테이블 cmn_relative_duration에 저장되며 다음으로 이동하여 검사할 수 있습니다. 시스템 스케줄러 > 일정 > 상대 기간. 바로 사용 가능한 인스턴스에 몇 가지 상대 기간 스크립트 예가 있습니다.

    상대 기간 sys_id는 초기화 후 전역 API DurationCalculator 클래스의 calcRelativeDuration() 메서드에 전달됩니다. 이 메서드를 호출하면 DurationCalculator 개체가 상대 기간 스크립트(테이블 cmn_relative_duration에 저장됨)에 변수 계산기로 전달됩니다. 따라서 사용자가 작성하고 cmn_relative_duration에 저장하는 상대 기간 스크립트는 변수 계산기를 통해 실행 중인 DurationCalculator에 액세스할 수 있습니다.

    다음 스크립트에서는 DurationCalculator 를 사용하여 상대 기간을 계산하는 방법을 보여 줍니다.
    /**
     * Sample use of relative duration calculation.
     * 
     */
     
    gs.include('DurationCalculator');
    executeSample();
     
    /**
     * Function to house the sample script.
     */
    function executeSample(){
     
        // First we need a DurationCalculator object. We will also use
        // the out-of-box relative duration "2 bus days by 4pm"
        var dc = new DurationCalculator();
        var relDur = "3bf802c20a0a0b52008e2859cd8abcf2"; // 2 bus days by 4pm if before 10am
        addSchedule(dc);
     
        // Since our start date is before 10:00am our result is two days from// now at 4:00pm.
        var gdt = new GlideDateTime("2012-05-01 09:00:00");
        dc.setStartDateTime(gdt);
        if(!dc.calcRelativeDuration(relDur)){
          gs.log("*** calcRelativeDuration failed");
          return;
        }
        gs.log("Two days later 4:00pm: "+ dc.getEndDateTime());
     
        // Since our start date is after 10:00am our result is three days from
        // now at 4:00pm.
        var gdt = new GlideDateTime("2012-05-01 11:00:00");
        dc.setStartDateTime(gdt);
        if(!dc.calcRelativeDuration(relDur)){
          gs.log("*** calcRelativeDuration failed");
          return;
        }
        gs.log("Three days later 4:00pm: "+ dc.getEndDateTime());}
     
    /** 
     * Add a specific schedule to the DurationCalculator object.
     *  
     * @param durationCalculator An instance of DurationCalculator
     */
    function addSchedule(durationCalculator){
        // Load the "8-5 weekdays excluding holidays" schedule into our duration calculator.
        var scheduleName ="8-5 weekdays excluding holidays";
        var grSched =new GlideRecord('cmn_schedule');
        grSched.addQuery('name', scheduleName);
        grSched.query();
        if(!grSched.next()){
          gs.log('*** Could not find schedule "'+ scheduleName +'"');
          return;}
        durationCalculator.setSchedule(grSched.getUniqueValue(),"GMT");}