Calculate an End Date, taking working hours into account

The workflow management API exposes methods that allow you to add a timespan to a specific date, taking working hours defined in K2 into consideration, and return a datetime that was calculated by excluding non-working hours. The code below can be used to perform a calculation where the end date and time is calculated using a start date and time, the Working Hours Zone details and additional days, hours, minutes and seconds. 

This sample code requires references to the assemblies:

  • SourceCode.HostClientAPI
  • SourceCode.Workflow.Management

Copy

Calculate an End Date

//TODO: build a connection string with the SourceCode.Hosting.Client.BaseAPI.SCConnectionStringBuilder
SourceCode.Hosting.Client.BaseAPI.SCConnectionStringBuilder connectionString = new SCConnectionStringBuilder();
connectionString.Host = "[k2servername]";
//alternatively build a simple connection
WorkflowManagementServer workflowServer = new WorkflowManagementServer("localhost", 5555);

try {
    //declare variables
    string zone = "[ZoneName]"; //The name of the working hours zone which should be included in the calculation
    DateTime startDate = System.DateTime.Now; //The date that the calculation should start from
    int days = 1; //The amount of days to be added to the start date
    int hours = 2; //The amount of hours to be added to the start date
    int minutes = 3; //The amount of minutes to be added to the start date
    int seconds = 4; //The amount of seconds to be added to the start date

    workflowServer.Open();

    //use a specific zone's working hours
    DateTime specificZoneEndDate = workflowServer.ZoneCalculateEvent(zone, startDate, new TimeSpan(days, hours, minutes, seconds));
    //or, use the default working hours zone
    DateTime defaultZoneEndDate = workflowServer.ZoneCalculateEvent(startDate, new TimeSpan(days, hours, minutes, seconds));
} catch(Exception ex) {
    //do something with the error
    throw ex;
} finally {
    //always close the connection
    workflowServer.Connection.Close();
}

Example:

Assuming:

  • zone = “MyDefaultWorkHoursZone” (this zone is specified to have working hours Mondays to Fridays from 8am to 5pm)
  • calcStartDate = 2012/11/08 13:00:00pm
  • days = 0
  • hours = 20
  • minutes = 0
  • seconds = 0
the result will be 2012/11/12 15:00:00pm, because:
  • Thursday (2012/11/08) 1pm to 5pm = 4 hours
  • Friday 8am to 5pm = 9 hours (7 hours remaining of the 20 hours specified)
  • Monday 8am + 7 hours = 15:00:00pm
  • Saturday and Sunday are not taken into consideration as it is specified as non-working days in the specified zone.