Skip to content
Advertisement

Return the average time difference between dates excluding “Non-Working hours”

I am making a ticketing system for my company. In my database I record the timestamp of when a ticket is first raised and a timestamp of when the ticket is marked as completed.

I have written a function which returns the average time (hrs) a ticket takes to complete:

JavaScript

Is there a way I could exclude certain hours? For example our office is open from 09:00-17:00 Monday to Friday.

At the moment if a ticket is raised at 16:30 on a Friday and is completed 09:15 on Monday the average time would be quite high when actually the ticket only took 45 minutes of working time.

Result of var_export():

JavaScript

Advertisement

Answer

You will have to loop over the dates between ticketCreated and ticketCompletedOn day by day. There seems to be no mathy way(or at least not in readable format) to solve this as you have time constraints of excluding Saturdays and Sundays as well as the working period being from 09:00:00 to 17:00:00.

Snippet:

JavaScript

Demo: https://3v4l.org/gpFt4

Explanation:

  • We first create DateTime instances of the dates.
  • We now have a do while loop inside.
  • If the end time and start time fall on the same day, we just take differences in terms of hours, minutes and seconds.
  • If the end time and start time doesn’t fall on the same day, then we subtract the times from start_time from end_of_day which will be 480 minutes for a proper start or remaining offset of that day till 17:00:00.
  • If we come across a day which is Saturday or Sunday, we just skip it.
  • In the end, we just print the average by dividing sum by total number of tickets.
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement