Calculate difference of two date on a schedule
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-09-2024 10:31 AM
I need to calculate the time from the created and a depart date on a 8-5 MF schedule that i have in place in the system
var sched = 'the schedules sys_id'; //M-F Weekdays Excl Holidays
var scheduleGR = new GlideSchedule(sched);
var RecordGR = new GlideRecord('my table name');
if (RecordGR.get(recordID)) {
var departure_date = new GlideDateTime(RecordGR.departure_date);
var created_date = new GlideDateTime(RecordGR.sys_created_on);
var difference = scheduleGR.departure_date.getNumericValue() - scheduleGR.created_date.getNumericValue();
var totalDuration = (difference / (1000 * 60 * 60)); //Converts Milliseconds to Hours
return totalDuration;
}
Everything works fine if i remove the scheduleGR in the var difference = .... lines and i get the hours of the two dates but that include holidays and weekends. Any way to do this?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-09-2024 12:41 PM - edited 05-09-2024 03:53 PM
Seem you are not using any schedule, but it you want hours between two date-time field on a table record, try the following
var sched = '090eecae0a0a0b260077e1dfa71da828'; //M-F Weekdays Excl Holidays
var scheduleGR = new GlideSchedule(sched);
var RecordGR = new GlideRecord('u_test_table');
// recordId is not defined, will use a sys_if of a record in my table
// if (RecordGR.get(recordID)) {
if (RecordGR.get('1875c3ca978dc290cd57fca6f053af87')) {
// var departure_date = new GlideDateTime(RecordGR.departure_date);
// var created_date = new GlideDateTime(RecordGR.sys_created_on);
// use fields defined on the table
var startDate = new GlideDateTime(RecordGR.u_start_date);
var endDate = new GlideDateTime(RecordGR.u_end_date);
gs.info("u_start_date = " + RecordGR.u_start_date + ", startDate " + startDate + ", u_end_date = " + RecordGR.u_end_date + ", endDate = " + endDate);
// No field named 'departure_date' defined on cmn_schedule, no field named 'created_date' on cmn_schedule
// var difference = scheduleGR.departure_date.getNumericValue() - scheduleGR.created_date.getNumericValue();
var difference = endDate.getNumericValue() - startDate.getNumericValue();
var totalDuration = (difference / (1000 * 60 * 60)); //Converts Milliseconds to Hours
// return totalDuration;
gs.info("Duration is " + totalDuration);
}
Tested in scripts background, result:
*** Script: u_start_date = 2024-03-22 17:01:35, startDate 2024-03-22 17:01:35, u_end_date = 2024-03-25 17:01:35, endDate = 2024-03-25 17:01:35
*** Script: Duration is 72
Seems you need another means to verify your two date-time fields are within the schedule when the record is created/updated.