treycarroll
Giga Guru

All,

I am using this DurationCalculator facade object to simplify a duration calculation for the most common use-case that we face.

//@param strDateTime1: string in YYYY-MM-DD hh:mm:ss format

//@param strDateTime2: string in YYYY-MM-DD hh:mm:ss format

//@param scheduleId: sys_id for entry in cmn_schedule.   If omitted, the 8-5 week days excluding holidays schedule will be used

//Never returns a negative number. If strDateTime2 precedes strDateTime1 getDurationSeconds will return zero

//Prevents troublesome off by GMT offset errors

//getDurationSeconds() is the only public method exposed on this object

var u_durationCalculator = function (strDateTime1, strDateTime2, scheduleId) {  

 

      var outerScope = this;  

      //If they didn't provide a schedule ID default to the 8-5 week days excluding holidays schedule  

      this.scheduleId = (!JSUtil.nil(scheduleId)) ? scheduleId : '090eecae0a0a0b260077e1dfa71da828';    

      this.timeZone = gs.getSession().getTimeZone();  

      this.dt1 = correctStringDateTimeForGMT(strDateTime1);  

      this.dt2 = correctStringDateTimeForGMT(strDateTime2);  

 

  // Convert the string parameter to GlideDateTime using the assumption that the string provided was user TZ localized and needs to be converted to GMT

      function correctStringDateTimeForGMT(stringDateTime) {  

              var dt = new GlideDateTime(stringDateTime);  

              dt.getLocaltime();  

              var offSetInSeconds = dt.getTZOffset() / 1000; //convert from millis  

              var multiplier = (offSetInSeconds < 0) ? -1 : 1;  

              dt.addSeconds(multiplier * offSetInSeconds);  

              return dt;  

      }  

 

      function getDurationSeconds() {  

              var dc = new DurationCalculator();  

              dc.setSchedule(outerScope.scheduleId, outerScope.timeZone);  

              var ans = dc.calcScheduleDuration(outerScope.dt1.getDisplayValue(), outerScope.dt2.getDisplayValue());  

              return ans;  

      }  

 

      return {  

              getDurationSeconds: getDurationSeconds  

      };  

};  

 

//Example usage  

var dc = new u_durationCalculator ('2016-02-19 12:00:00', '2016-02-22 09:30:00');  

gs.print('Duration Hours:' + dc.getDurationSeconds() / 3600);  

//Output  

*** Script: Duration Hours:6.5  

The "façade " design pattern is used to provide a simplified interface.   Those who have used the existing DateTime function library may have also stumbled into the pitfalls.   I would love it if others were interested in joining me in an effort to create other facade objects for common use-cases involving DateTime calculations.

Godspeed,

Trey Carroll

1 Comment