Add hours to a date excluding weekends.

Hi
I have to write a function to calculate the SLA Due Date by adding hours to the startDate of a ticket. But it should add HRS by excluding weekend Hours.
SLA Would be in HRS... For example, if Ticket was opened on Friday 4PM and SLA is 24 hours, the SLADUEDate should be Monday 4PM Not Saturday 4PM. 
Moreover if the SLA is 12 hours, The SLADueDate should be 4AM Monday. 
I do not have a date table to accomplish this So i am thinking how to tackle this.
Can anyone help me out with the logic for the function. 
Thanks 
Rajiv 
Rajiv

If creating a calendar table is an option, this is simple:
DECLARE @calendar TABLE (date date, isWeekend bit, isHoliday bit)
INSERT INTO @calendar (date, isWeekend, isHoliday)
VALUES
('2014-09-21',1,0),('2014-09-22',0,0),('2014-09-23',0,0),('2014-09-24',0,0),('2014-09-25',0,0),('2014-09-26',0,0),('2014-09-27',1,0),
('2014-09-28',1,0),('2014-09-29',0,0),('2014-09-30',0,0),('2014-10-01',0,0),('2014-10-02',0,0),('2014-10-03',0,0),('2014-10-04',1,0)
DECLARE @tickets TABLE (ticketID INT IDENTITY, ticketstartDateTime DATETIME)
INSERT INTO @tickets (ticketstartDateTime)
VALUES
('2014-09-23 18:22:33'),('2014-09-24 13:11:54'),('2014-09-25 16:33:14'),('2014-09-26 11:22:33')
SELECT t.*, CONVERT(DATETIME,CONVERT(VARCHAR,c.date,101) + ' ' + CONVERT(varchar,ticketstartDateTime,108)) AS SLADateTime
FROM @tickets t
INNER JOIN @calendar c
ON c.date = (SELECT MIN(date)
FROM @calendar
WHERE date > t.ticketstartDateTime
AND isWeekend = 0
AND isHoliday = 0
If not, try:
DECLARE @tickets TABLE (ticketID INT IDENTITY, ticketstartDateTime DATETIME)
INSERT INTO @tickets (ticketstartDateTime)
VALUES
('2014-09-23 18:22:33'),('2014-09-24 13:11:54'),('2014-09-25 16:33:14'),('2014-09-26 11:22:33')
;WITH rCTE AS (
SELECT DATEADD(DAY,10,GETDATE()) AS date, 10 AS mod
UNION ALL
SELECT DATEADD(DAY,-1,r.date) AS date, mod-1 as mod
FROM rCTE r
WHERE mod > -30
), pCal AS (
SELECT r.*, CASE WHEN h.date IS NOT NULL THEN 1 ELSE 0 END AS isHoliday, CASE WHEN DATEPART(WEEKDAY,r.date) IN (7,1) THEN 1 ELSE 0 END AS isWeekend
FROM rCTE r
LEFT OUTER JOIN (SELECT * FROM holidays(YEAR(GETDATE()))) h
ON r.date = h.date
SELECT t.*, CONVERT(DATETIME,CONVERT(VARCHAR,c.date,101) + ' ' + CONVERT(varchar,ticketstartDateTime,108)) AS SLADateTime
FROM @tickets t
INNER JOIN pCal c
ON c.date = (SELECT MIN(date)
FROM pCal
WHERE date > t.ticketstartDateTime
AND isWeekend = 0
AND isHoliday = 0
Note that Holidays() is a function capable of returning holiday dates for your area.

Similar Messages

  • Calcuate Hours: Minutes:Seconds between two dates excluding Weekends

    Hello All,
    @StartDate = '2014-06-21 13:37:30:037'
    @EndDate = GetDate()
    I want to find out Hours:Minutes:Seconds between the above dates EXCLUDING WEEKENDS.
    Please help.
    ReportingServices

    Hi,
    Give this a try:
    DECLARE @StartDate DATETIME = '2014-06-21 13:37:30:037'
    DECLARE @EndDate DATETIME = GETDATE()
    DECLARE @Base INT = 86400 -- ie Seconds in a days
    ;WITH cteCalculation AS (
    SELECT ((
    (DATEDIFF(dd, @StartDate, @EndDate) + 1)
    -(DATEDIFF(wk, @StartDate, @EndDate) * 2)
    -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
    -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
    ) * @Base)
    -(CASE WHEN DATENAME(dw, @StartDate) NOT IN ('Saturday', 'Sunday') THEN DATEPART(hh, @StartDate) * 3600 + DATEPART(mi, @StartDate) * 60 + DATEPART(ss, @StartDate) ELSE 0 END)
    -(CASE WHEN DATENAME(dw, @EndDate) NOT IN ('Saturday', 'Sunday') THEN @Base - (DATEPART(hh, @EndDate) * 3600 + DATEPART(mi, @EndDate) * 60 + DATEPART(ss, @EndDate)) ELSE 0 END)
    AS DiffInSec
    SELECT @StartDate
    ,@EndDate
    ,CAST(DiffInSec / 3600 AS VARCHAR(10)) + ':' +
    RIGHT('0' + CAST((DiffInSec % 3600) / 60 AS VARCHAR(2)), 2) + ':' +
    RIGHT('0' + CAST((DiffInSec % 3600 % 60) AS VARCHAR(2)), 2)
    FROM cteCalculation
    Feel free to modify to suit your needs!
    Hope this helps.
    ~J.

  • Function module in SRM for adding number to date excluding weekends

    Hi Experts,
    Please help to get the standard FM in SRM for adding number to date and getting next date excluding weekends.
    Thanks in Advance.
    Thanks,
    Sahil

    This kind of custom FM can be created easily.
    But if you want to use standard FM then "DATE_CONVERT_TO_FACTORYDATE" FM is good but you need a factory calendar id which has all working days and weekend days specified (also public holidays if required). Then call this FM in loop for a count of days and it will give working day after "entered date + number of days"
    So if calendar has only weekdays and weekends specified, it will add number of days in specified date excluding weekends.
    Thanks,
    Murtuza

  • Add working days to a date excluding weekends and holidays

    Hi there,
    I need to write a function that will take a specified date and number of days to add as input parameters, and return the working day based on the number of days to add parameter, excluding weekends and any holidays held in a holiday table.
    Here is my function so far -
    CREATE OR REPLACE FUNCTION f_add_work_days(pd_date IN DATE
    ,pn_add_days IN PLS_INTEGER) RETURN DATE IS
    pd_in_date DATE := pd_date;
    ld_next_holiday DATE;
    ln_days_left PLS_INTEGER := pn_add_days;
    CURSOR cu_holiday(pn_date IN ge740.holdte%TYPE) IS
    SELECT pck_utility.f_dtcnv(g.holdte)
    FROM ge740 g
    WHERE g.holdte >= pn_date
    AND g.maint <> 'D'
    ORDER BY g.holdte ASC;
    BEGIN
    OPEN cu_holiday(pck_utility.f_dtcnv(pd_in_date));
    FETCH cu_holiday
    INTO ld_next_holiday;
    CLOSE cu_holiday;
    LOOP
    IF ln_days_left = 0 THEN
    EXIT;
    END IF;
    pd_in_date := pd_in_date + 1;
    IF pd_in_date > ld_next_holiday THEN
    OPEN cu_holiday(pck_utility.f_dtcnv(pd_in_date));
    FETCH cu_holiday
    INTO ld_next_holiday;
    CLOSE cu_holiday;
    END IF;
    CASE
    WHEN TO_CHAR(pd_in_date
    ,'fmDAY') = 'SATURDAY' THEN
    pd_in_date := pd_in_date + 2;
    ln_days_left := ln_days_left - 1;
    WHEN TO_CHAR(pd_in_date
    ,'fmDAY') = 'SUNDAY' THEN
    pd_in_date := pd_in_date + 1;
    ln_days_left := ln_days_left - 1;
    WHEN pd_in_date = ld_next_holiday THEN
    pd_in_date := pd_in_date + 1;
    ln_days_left := ln_days_left - 1;
    ELSE
    ln_days_left := ln_days_left - 1;
    END CASE;
    END LOOP;
    RETURN(pd_in_date);
    END f_add_work_days;
    I think there is something wrong/missing in the logic as I can't get it to cater for say a double bank holiday(25/26th Dec - if the input parameters are 24/12/2007 and 2, which should return the 28th but returns the 26th!!).
    I'm relatively new to PL/SQL and Oracle, so any help, advice, ideas would be greatly appreciated!
    thanks in advance

    smth like
    SQL> with holidays as (select to_date('10.06.2007','dd.mm.yyyy') h_dt from dual),
      2       par as (select to_date('08.06.2007','dd.mm.yyyy') dt, 2 add_days from dual)
      3  --
      4  select min(dt) needed_date
      5    from (select p.*,
      6                 h.*,
      7                 mod(to_char(dt, 'j'), 7),
      8                 sum(decode(mod(to_char(dt, 'j'), 7), 5, 0, 6, 0, 1)+--get rid of sat and sun
      9                     nvl2(h_dt, -1, 0)--check if the day is holiday
    10                     ) over(order by dt) s
    11            from (select dt + level dt, add_days
    12                    from par
    13                  connect by level <= 100) p,
    14                 holidays h
    15           where h_dt(+) = dt
    16           order by 1)
    17   where add_days = s
    18  /
    NEEDED_DATE
    13.06.2007
    SQL> ?
    Message was edited by:
    Volder
    PS What Oracle version are you on?

  • Time between dates excluding Weekends and Holidays

    I am fairly new to Power Pivot and I am having trouble with this formula.  I need my Cycle Time Days column to capture the days between CreatedDataTime and ClosedDateTime excluding Weekends and Holidays.  I have a tab that has the holidays but
    I can't get the formula correctly?   Jill
    CreatdDateTime        ClosedDateTime     Cycle Time Days
    12/1/2014                    12/10/2014

    first of all you need a separate time table which holds all possible dates for your model
    there should be no gaps, it should contain full years and a column of datatype DateTime as unique key
    once you have this in place add a calculated column to this table as 
    =IF(INT(FORMAT([Date], "w")) >= 6, "Weekend", "Workday")
    then go back to your original table and add the following calculation for your [Cycle Time Days]-column:
    =COUNTROWS(
    FILTER(
        'Dates',
        Dates[Date] >= DateRanges[DateFrom]
        && Dates[Date] <= DateRanges[DateTo]
        && 'Dates'[IsWeekend] = "Workday"
    Holidays are a bit more tricky but you can follow the same pattern but you need to get the holidays from somewhere
    hth,
    -gerhard
    Gerhard Brueckl
    blogging @ http://blog.gbrueckl.at
    working @ http://www.pmOne.com

  • How to get difference in days between 2 dates excluding weekends

    Hi all,
    i have a requirement, to calculate the difference between 2 dates, in days.
    eg: 01/08/2007 and 05/08/2007.
         Difference = 4 days.
    But here my actual requirement is i have to calculate this difference excluding weekends (saturday n sundays).
    eg: 01/08/2007 -
    Thursday
         05/08/2007 -
    Monday
    so now Difference = 2 days.
    Please help me regarding this.
    Points will be rewarded for helpfull answers.
    Thanks in Advance.
    Regards,
    Vineel

    see these codes of rich
    report zrich_0003.
    data: begin of itab occurs 0,
          datum type sy-datum,
          end of itab.
    data: weekday like dtresr-weekday.
    data: number_lines type i.
    parameters: p_sdatum type sy-datum,
                p_edatum type sy-datum.
    itab-datum = p_sdatum.
    append itab.
    do.
      if itab-datum = p_edatum.
        exit.
      endif.
      itab-datum = itab-datum + 1.
      call function 'DATE_TO_DAY'
           exporting
                date    = itab-datum
           importing
                weekday = weekday.
      if weekday = 'Sat.'
        or weekday = 'Sunday'.
        continue.
      endif.
      append itab.
    enddo.
    describe table itab lines number_lines.
    write:/ 'Number of days between dates is', number_lines.
    and
    report zrich_0001.
    parameters: p_start type sy-datum,
                p_end   type sy-datum.
    data: idays type table of   rke_dat with header line.
    data: workingdays type i.
    call function 'RKE_SELECT_FACTDAYS_FOR_PERIOD'
         exporting
              i_datab               = p_start
              i_datbi               = p_end
              i_factid              = 'P8'  " Fact Calender ID
         tables
              eth_dats              = idays
         exceptions
              date_conversion_error = 1
              others                = 2.
    describe table idays lines workingdays.
    write:/ workingdays.
    I want to find the No.of working days between the two dates
    regards,
    srinivas

  • Calculate the Difference Between two dates excluding weekends and Holidays

    Hi,
    We need to calculate the difference between the two dates by excluding the Local public holidays (It is global and varies across countries) and weekends should not be included in calculation for a business day in OBIEE.
    We have two dates: Open date and close date when ever close date is null we are calculating age based on taking the current timestamp and need to exclude the weekends and Holidays when ever the close date is null.
    Ex:
    Col1 col2 Total
    11/9/2010 2:46:38 PM Null 13
    11/2/2010 8:06:26 PM 11/3/2010 5:37:03 PM 1
    (In the Total we shouldn't include the weekends,holidays)
    Please let me know how to calculate the difference between two dates by excluding the weekends and holidays.
    Thanks
    Edited by: user10441472 on Nov 22, 2010 3:14 PM

    You already asked this question and I answered it...
    Re: calculation of Business day in OBIEE

  • Fucntion to Calculate business days (exclude weekends & holidays) between two days

    Hello,
    I need to be able to calculate business days between two dates excluding weekends and holidays. I do have a date dimension and also flags which denote weekday, holiday. Would really appreciate help in building a udf for the business days calculation.
    Thanks,

    Hi, Please take a look and tweak accordingly. Best of luck.
    --Assuming data dimension table something like the following
    --tblDateDim (DT date primary key,
    flagHoliday bit,
    flagWeekday bit
    CREATE FUNCTION fnBusinessDays (
    @StartDate DATE,
    @EndDate DATE
    RETURNS INT
    AS
    BEGIN
    DECLARE @Days INT ;
    SELECT @Days = count(*)
    FROM tblDateDim --// date dimension
    WHERE
    ( DT BETWEEN @StartDate AND @EndDate) --// dt is date column in the table.
    AND --// also flags which denote weekday, holiday
    flagHoliday = 0 --// flagHoliday= 1--Holiday;= 0 --workingday/businessday
    AND
    flagWeekday = 1 --// FlagWeekday = 1--businessday ; =0 --weekend (Saturday and Sunday)
    RETURN (@Days)
    END
    GO

  • ABAP HR- calculation of workind days (excluding weekend) for an employee

    Hi,
    I need to get number of working days between two dates excluding weekends for an employee. Please let me know below questions in this regard:
    1. I have to use Factory calender or holiday calender for this purpose?
    2. Will FM RKE_SELECT_FACTDAYS_FOR_PERIOD solve this purpose ?
    Regards,
    Aleria

    Hi Aleria,
    Use the FM DAY_ATTRIBUTES_GET in this FM pass the holiday and factory calendar of the employee along with the period. In the output structure if free day is set then it is SAT/SUN and if holiday is set then it is Public holiday marked in the calendar.
    Regards
    Bala

  • Calculating days excluding weekends

    Msy you please show me how to calculate the number of days in between 2 dates excluding weekends.

    Hi!
    Check out these FM-s:
    K_ABC_WORKDAYS_FOR_PERIODS_GET
    WEEK_GET_NR_OF_WORKDAYS      
    WLB3_GET_NUMBER_OF_WORKDAYS  
    There are some calendar relevant FM-s also. If there's set a production calendar in your SAP, you can check it also.
    SE37 transaction, and search for CALENDAR fm.
    Regards
    Tamá

  • Count number of hours between dates excluding holidays/weekends

    Hello all
    I havent worked with dates extensively and was recently asked to create a report where Im looking for the number of hours between two dates only counting business days.
    So for example I have data as follows
    Created 2011-03-30 15:00:00
    Processed 2011-03-30 15:03:46
    Fulfilled 2011-04-01 17:25:02
    Mailed     2011-04-01 17:45:00
    For a total of looking from the CREATED and MAILED dates
    50 hours 45 minutes
    Im also trying to exclude weekends and holidays, i was reading around and was actually able to also find a table of dates where I have the main date, HOLIDAY_IND column and WEEKDAY_IND column
    So the calender table i have looks similar to
    CALENDER_DATE HOLIDAY_IND WEEKDAY_IND
    2011-03-31 Y Y
    2011-04-01 N Y
    2011-04-02 N N
    Im really quite stumped as to where to begin
    I was thinking of trying to write it with PL/SQL but i dont have the proper user access to create procedures/functions, so looks like straight up SQL
    Any help appreciated!

    Hi,
    Depeneding on your data and your requirements, you can do something like this:
    SELECT     created_DATE,
    ,     mailed_date
    ,     24 * ( (mailed_date - created_date)
                SELECT  COUNT (*)
                FROM        table_o_dates
                WHERE    main_date > created_date
                AND        main_date < TRUNC (mailed_date)
                AND        (   holiday_ind = 'Y'
                         OR  weekday_ind = 'N'
               )               AS hours_between       
    FROM     table_x
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables, and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say which version of Oracle you're using.
    What do you want to do if created_date or mailed_date is not a work day? Include examples in you data and results.

  • Confused - How to Calculate Number of Days Between Dates but Exclude Weekend Dates If There Hasn't Been a Weekend Update

    Hello -
    I've been tearing my hair out over this problem i'm trying to solve, probably just been staring at it too long which is making it worse -
    I have a series of open support tickets which are supposed to be updated on a daily basis, the problem is that they aren't always being updated daily.  So, the business wants to know the number of days from when a ticket was last updated and today's
    date.  I have this basic calculation and it's working fine, however now the business wants to exclude weekends from the calculation.  The other problem is that some reps DO go in on weekends and update their tickets, so sometimes there will be updates
    made on weekend dates.
    To give an example -
    Today's date is 2014-02-10 (Monday).  A ticket was last updated last Thursday, 2014-01-30.  The difference between the two dates is 11, so it's been 11 days since the ticket was last updated.  Now, if I exclude Saturdays and Sundays, then
    it's actually been 7 days since the ticket was last updated.  I'm not sure how to do this in T-SQL.
    Now, to further complicate the problem, sometimes a ticket IS updated on a Saturday or Sunday.  So, if a ticket was updated on 2014-02-02 (Sunday), then it should be counted.  Again i'm not sure how to do this. 
    What gets me is that this is probably fairly simple and i've just been staring at it too long.  In the meantime, can someone offer some guidance?
    Thanks!!

    I've adapted this from a function on my blog. you will need to add set the YourTicketTable to where ever your tickets are stored.
    CREATE
    FUNCTION [dbo].[CalcWorkDaysBetween](@StartDate
    As DateTime,@EndDate
    AS DateTime)
    RETURNS
    INT AS
    BEGIN
    SET @EndDate
    =DATEADD(DAY,1,@EndDate)
    DECLARE @Count
    AS Int= 0
    DECLARE @Date
    As Date=@StartDate
    WHILE @Date
    < @EndDate
    BEGIN
    IF (DATEPART(WEEKDAY,@Date)IN(1,7)
    OR (SELECT
    Count(*)
    FROM YourTicketTable WHERE TicketDate=@Date)=1)
    BEGIN
    SELECT @Count = @Count
    + 1
    END
    SELECT @Date=DATEADD(Day,
    1,@Date)
    END
    RETURN
    DATEDIFF(DAY,@StartDate,@EndDate)- @Count
    END
    Regards,

  • Exclude weekends when substracting between two date values

    Hi All,
    I created a variable to get the value between 2 date values.
    v_lag_days := TRUNC (l_header_rec.request_date) - TRUNC (SYSDATE);
    if l_header_rec.request_date = sysdate i.e. 17-Feb-12 then it is fine, I will get the value as '0' which is correct.
    But if l_header_rec.request_date = '20-Feb-12' (for example), it will give me as '3', but I should get the value as '1' excluding weekends.
    When ever with in the 2 date values if it contains weekends, it should exclude those weekend days and should give me the value in the variable.
    If you are not able to get my point clearly, please let me know.
    Could anyone please let me know the logic for my scenario. Please help me out that would be really appreciated.
    Thanks in advance,
    Satya.

    Hi Satya.
    This is the same example, without including the final day.
    WITH aux1 AS
         SELECT
              CASE WHEN TO_NUMBER(TO_CHAR(TO_DATE(:date1,'YYYYMMDD')+(LEVEL-1),'D')) >= 6
                   THEN 0
                   ELSE 1
              END inc
         FROM dual
         CONNECT BY LEVEL <= (TO_DATE(:date2,'YYYYMMDD') - TO_DATE(:date1,'YYYYMMDD'))
    SELECT SIGN(:date2 - :date1)*SUM(inc) num_of_days FROM aux1;
    -- ':date2 = 20120217'
    -- ':date1 = 20120210'
    NUM_OF_DAYS
              5
    -- ':date2 = 20120220'
    -- ':date1 = 20120217'
    NUM_OF_DAYS
              1
    -- ':date2 = 20120217'
    -- ':date1 = 20120217'
    NUM_OF_DAYS
              0Hope this helps.
    Best Regards
    Edited by: sKr on 17-feb-2012 9:04 Improved for date2 = date1

  • How to exclude weekends & holidays from a date range

    Hi Friends,
    How can I exclude weekends & other holidays (which are specific to that country only) from a given range of date (if any weenends or holiday falls in that range)?
    Please supply some sample code if possible.
    Thanks in advance.

    Enayats_screen wrote:
    Hi
    I have found the relevant code for your help. May be this will solve your purpose. Please visit the below link
    http://www.simplyshareit.net/itemDetails.jsf?q=532&
    Thanks.Whew! Thank the gods you saved the OP from having to actually think or learn or clearly communicate his problem!

  • Excluding Weekend dates from existing query

    I have the following query that returns the average of the total sum between start and end date of a status.
    How do I take out the weekend dates so it doesn't include saturday and sunday.?
    SELECT TRUNC(AVG( SUM ( (DECODE (status, 'Estimator Notified' ");
    ,cc.end_date,NULL) - DECODE (cc.status, 'Estimator Notified',cc.start_date,NULL)))),1)
    FROM cc_request_status cc
    group by cc.request_id

    The above solution actually generates each date in a range and tests it for a Saturday or Sunday date. A more efficient solution calculates the weekend days directly by using the following facts:
    1) For each whole week in the range the number of weekends days is 2.
    2) For the partial week, a function can be made based on the ending day and the number of partial days to calculate the number of weekend days.
    The following code uses the above two facts to calculate the number of days in a range excluding weekends:
    SELECT NUM_DAYS - (WEEKS*2) -
           CASE WHEN REMAINDER = 0 THEN 0
                WHEN END_DOW = 7 THEN 1
                ELSE
                    CASE
                        WHEN END_DOW > REMAINDER THEN 0
                        WHEN END_DOW = REMAINDER THEN 1
                        ELSE 2
                    END
           END BUS_DAYS
    FROM
        SELECT END_DOW, NUM_DAYS, FLOOR(NUM_DAYS/7) WEEKS, MOD(NUM_DAYS,7) REMAINDER
        FROM
            SELECT (TO_NUMBER(TO_CHAR(END_DATE, 'J')) -
                    TO_NUMBER(TO_CHAR(START_DATE, 'J'))) + 1 NUM_DAYS,
                   TO_NUMBER(TO_CHAR(END_DATE,  'D')) END_DOW
            FROM
              SELECT TO_DATE('05/05/2007','MM/DD/YYYY') START_DATE,
                     TO_DATE('05/14/2007','MM/DD/YYYY') END_DATE
              FROM DUAL
    );You can collapse some of the inline views down, I expanded them to show each step.
    JR

Maybe you are looking for