Date difference function that returns minutes between two dates and excludes weekends and holidays

Is there a way to get this to work as a function? 
Currently returns error "Select statements included within a function cannot return data to a client"
CREATE FUNCTION [dbo].[WorkDays](@DateFrom datetime,@DateTo datetime)
RETURNS int
AS
BEGIN
--Working time
DECLARE @WTFrom TIME = '8:00AM';
DECLARE @WTTo TIME = '5:00PM';
DECLARE @minCount BIGINT
--Date ranges
IF (DATEDIFF(HOUR, @DateFrom, @DateTo) > 12)
BEGIN
WITH CTE AS
SELECT @DateFrom AS DateVal
UNION ALL
SELECT DATEADD(HOUR, 1, DateVal)
FROM CTE
WHERE DateVal < DATEADD(HOUR, -1,@DateTo)
SELECT DATEDIFF(minute, MIN(CTE.DateVal), MAX(CTE.DateVal))
FROM CTE
WHERE (CAST(CTE.DateVal AS time) > @WTFrom AND CAST(CTE.DateVal AS time) < @WTTo) AND DATEPART(dw, CTE.DateVal) NOT IN (1, 7) AND NOT EXISTS (SELECT * FROM Holiday AS H WHERE H.holiday = CTE.DateVal)
OPTION (MAXRECURSION 0);
END;
ELSE
BEGIN
WITH CTE AS
SELECT @DateFrom AS DateVal
UNION ALL
SELECT DATEADD(MINUTE, 1, DateVal)
FROM CTE
WHERE DateVal < DATEADD(MINUTE, -1,@DateTo)
SELECT DATEDIFF(minute, MIN(CTE.DateVal), MAX(CTE.DateVal))
FROM CTE
WHERE (CAST(CTE.DateVal AS time) > @WTFrom AND CAST(CTE.DateVal AS time) < @WTTo) AND DATEPART(dw, CTE.DateVal) NOT IN (1, 7) AND NOT EXISTS (SELECT * FROM Holiday AS H WHERE H.holiday = CTE.DateVal)
OPTION (MAXRECURSION 0);
END;
END
Thanks for your help.

Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules (you do not). Temporal
data should use ISO-8601 formats (you do not!). Code should be in Standard SQL as much as possible and not local dialect. 
This is minimal polite behavior on SQL forums. 
We hate functions in SQL. This is a declarative language and you are using it like 1950's FORTRAN. We hate local variables (more FORTRAN!)
 The name of a function has to be either a known, common name, like “sine”, “cosine” etc. Or it is “<verb>_<object>”; you think a noun is a verb! Do you really need BIGINT? Why did you invite garbage data with it? Why do you think that SQL
uses AM/PM? Have you never seen the TIME data type? 
Think about “date_val” as a data element name. A date is a unit of temporal measurement on a calendar scale. This would be a “<something>_date” in a valid schema. 
>> Is there a way to get this to work as a function? <<
Probably, but why do it wrong?
Build a calendar table with one column for the calendar data and other columns to show whatever your business needs in the way of temporal information. Do not try to calculate holidays in SQL -- Easter alone requires too much math.
The julian_business_nbr is how SQL people do this. Here is the skeleton. 
CREATE TABLE Calendar
(cal_date DATE NOT NULL PRIMARY KEY, 
 julian_business_nbr INTEGER NOT NULL, 
Here is how it works:
INSERT INTO Calendar 
VALUES ('2007-04-05', 42), 
 ('2007-04-06', 43), -- Good Friday 
 ('2007-04-07', 43), 
 ('2007-04-08', 43), -- Easter Sunday 
 ('2007-04-09', 44), 
 ('2007-04-10', 45); --Tuesday
To compute the business days from Thursday of this sample week to next Tuesday:
SELECT (C2.julian_business_nbr - C1.julian_business_nbr)
  FROM Calendar AS C1, Calendar AS C2
 WHERE C1.cal_date = '2007-04-05',
   AND C2.cal_date = '2007-04-10'; 
See how simple it can be when you stop trying to write FORTRAN and think in sets? 
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL

Similar Messages

  • Using pl/sql function for each day between two dates.

    Hi,
    create TABLE EMP(
    ID_EMP NUMBER,
    DT_FROM DATE,
    DT_TO DATE,
    CREATE_DATE DATE);
    into EMP(ID_EMP, DT_FROM, DT_TO, CREATE_DATE)
    Values(100, TO_DATE('07/01/2008 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('04/30/2010 00:00:00', 'MM/DD/YYYY HH24:MI:SS'),TO_DATE('05/08/2009 14:11:21', 'MM/DD/YYYY HH24:MI:SS'));
    I have a function called  elig_pay_dates(date p_date), which returns the code for  person payment eligibility for a particular date. For paid dates it's 'P' and for unpaid dates it's 'N'.
    How can I check this function between two dates for each day. Example : 07/01/2008 to 04/30/2010.
    By using this function with select I needs to display the dates when there is a change in status.
    I am expecting data in following manner from above logic(this is example):
    07/01/2008 --- 07/01/2009 ---'P'
    07/02/2009 -- 07/25/2009 ----'N'
    07/26/2009 -- 01/01/2010 ---'P'
    01/02/2010 -- 01/13/2010 --'N'
    01/14/2010 -- 01/18/2010 --'P'
    01/19/2010 -- 04/30/2010 -- 'N'
    I thought of looping for each day date but that seems to be expensive for online application. Is there any way that I can achieve this requirement with sql query ?
    Thanks for your help,

    Certainly not the best way to code the requirement, but it does achieve the result you are looking for in a fairly quick time
    create or replace
    function test_ret_paid_unpaid (p_date in date)
    return varchar2
    is
      v_ret     varchar2(1);
    begin
      if ( (p_date between to_date('07/02/2009', 'MM/DD/YYYY') and to_date('07/25/2009', 'MM/DD/YYYY') ) or
           (p_date between to_date('01/02/2010', 'MM/DD/YYYY') and to_date('01/13/2010', 'MM/DD/YYYY') ) or
           (p_date between to_date('01/19/2010', 'MM/DD/YYYY') and to_date('04/30/2010', 'MM/DD/YYYY') )
        then v_ret := 'N';
      else
        v_ret := 'Y';
      end if;
      return v_ret;
    end;
    Wrote file afiedt.buf
      1  with get_paid_unpaid as
      2  (
      3    select dt_from start_date, dt_to end_date, dt_from + level - 1 curr_date, test_ret_paid_unpaid(dt_from + level - 1) paid_unpaid,
      4           row_number() over (order by dt_from + level - 1) rn_start,
      5           row_number() over (order by dt_from + level - 1 desc) rn_end
      6      from test_emp
      7    connect by level <= dt_to - dt_from + 1
      8  ),
      9  get_stop_date as
    10  (
    11  select start_date init_date, end_date, curr_date, paid_unpaid,
    12         case when paid_unpaid != lag(paid_unpaid) over (order by curr_date) or rn_start = 1 or rn_end = 1
    13          then curr_date
    14          else null
    15         end start_date,
    16         case when paid_unpaid != lead(paid_unpaid) over (order by curr_date) or rn_start = 1 or rn_end = 1
    17          then curr_date
    18          else null
    19         end stop_date
    20    from get_paid_unpaid
    21  )
    22  select period, paid_unpaid
    23    from (
    24  select init_date, curr_date, start_date, end_date, stop_date,
    25         case when paid_unpaid = lead(paid_unpaid) over (order by curr_date)
    26                then nvl(start_date, init_date) || ' - ' || lead(stop_date, 1, end_date) over (order by curr_date)
    27              else null
    28         end period,
    29         paid_unpaid
    30    from get_stop_date
    31   where stop_date is not null or start_date is not null
    32         )
    33*  where period is not null
    12:06:10 SQL> /
    PERIOD                                             PAID_UNPAID
    01-JUL-08 - 01-JUL-09                              Y
    02-JUL-09 - 25-JUL-09                              N
    26-JUL-09 - 01-JAN-10                              Y
    02-JAN-10 - 13-JAN-10                              N
    14-JAN-10 - 18-JAN-10                              Y
    19-JAN-10 - 30-APR-10                              N
    6 rows selected.
    Elapsed: 00:00:00.35

  • Compare n kyf and m chanm of Top 10 Document-No.s between two dates

    Dear BW-Gurus,
    Our Customer want´s a query, which shows in the TOP 10 of some sales-doc´s and marks a line, if the key figures or a characteristic has changed from one date to an other date (Comparision of a sales document between two dates).
    We now created a query with all of the key figures restricted to the one date and to the compare date and to get an info, if something has changed extra key figures build by a forumular subtracting one kyf from another.
    We only want to show a TOP 10 list of the doc´s - but we have a very poor performance now.
    1) is it possible to build a kind of aggregate containing only the top10 doc´s ? - this will speed up the query enormously.
    2) We intend to compare the characterstics and kyfs by using virtual characeristic, which will do the comparison - do you think this is the right way?
    How would you solve such a problem?
    many thanks for your support.
    regards
    Jürgen

    Post Author: V361
    CA Forum: Formula
    I modified your formula and added  /0
        else (HalfDays := ((BusinessEndTime - time(FDay)) / 3600 + (time(LDay) - BusinessStartTime) / 3600);        FullDays := (FinalDays - 2) * 9;        Hours := HalfDays + FullDays /0;
    This causes the formula to fail, but in my version, it will show you the numbers it used during the calc.
    For 2007-10-01 to 2007-10-10 the variables are as below
    FDay: #2007-10-01 08:00:00#
    LDay: #2007-10-09 17:00:00#
    BusinessStartTime: #08:00:00#
    BusinessEndTime:  #17:00:00#
    BSTime : 8
    BETime: 17
    Days:9
    Weekends: 2
    FinalDays: 7
    StartDate: #2007-10-01#
    EndDate: #2007-10-09#
    HalfDays: 18
    FullDays: 45
    Hours: 0
    For 2007-10-01 to 2007-10-11 the variables are as below
    FDay: #2007-10-01 08:00:00#
    LDay: #2007-10-10 17:00:00#
    BusinessStartTime: #08:00:00#
    BusinessEndTime:  #17:00:00#
    BSTime : 8
    BETime: 17
    Days:10
    Weekends: 2
    FinalDays: 8
    StartDate: #2007-10-01#
    EndDate: #2007-10-10#
    HalfDays: 18
    FullDays: 54
    Hours: 0
    FullDays, looks wrong for sure, I assume it is supposed to be hours, but I don't think it is supposed to be subtracting 2 either.  Anyway, your hours is actually the sum of your halfdays and fulldays.
    Hope that helps,

  • Find gap between two dates from table

    Hello All,
    I want to find gap between two dates ,if there is no gap between two dates then it should return min(eff_dt) and max(end_dt) value
    suppose below data in my item table
    item_id    eff_dt           end_dt
    10         20-jun-2012     25-jun-2012
    10         26-jun-2012     28-jun-2012 There is no gap between two rows for item 10 then it should return rows like
    item_id eff_dt end_dt
    10 20-jun-2012 28-jun-2012
    item_id    eff_dt           end_dt
    12         20-jun-2012     25-jun-2012
    12         27-jun-2012     28-jun-2012 There is gap between two rows for item 12 then it should return like
    item_id eff_dt end_dt
    12 20-jun-2012 25-jun-2012
    12 27-jun-2012 28-jun-2012
    I hv tried using below query but it giv null value for last row
    SELECT   item_id, eff_dt, end_dt, end_dt + 1 AS newd,
             LEAD (eff_dt) OVER (PARTITION BY ctry_code, co_code, item_id ORDER BY ctry_code,
              co_code, item_id) AS LEAD,
             (CASE
                 WHEN (end_dt + 1) =
                        LEAD (eff_dt) OVER (PARTITION BY ctry_code, co_code, item_id ORDER BY ctry_code,
                         co_code, item_id, eff_dt)
                    THEN '1'
                 ELSE '2'
              END
             ) AS new_num
      FROM item
       WHERE TRIM (item_id) = '802'
    ORDER BY ctry_code, co_code, item_id, eff_dtI m using oracle 10g.
    please any help is appreciate.
    Thanks.

    Use start of group method:
    with sample_table as (
                          select 10 item_id,date '2012-6-20' start_dt,date '2012-6-25' end_dt from dual union all
                          select 10,date '2012-6-26',date '2012-6-26' from dual
    select  item_id,
            min(start_dt) start_dt,
            max(end_dt) end_dt
      from  (
             select  item_id,
                     start_dt,
                     end_dt,
                     sum(start_of_group) over(partition by item_id order by start_dt) grp
               from  (
                      select  item_id,
                              start_dt,
                              end_dt,
                              case lag(end_dt) over(partition by item_id order by start_dt)
                                when start_dt - 1 then 0
                                else 1
                              end start_of_group
                        from  sample_table
      group by item_id,
               grp
      order by item_id,
               grp
       ITEM_ID START_DT  END_DT
            10 20-JUN-12 26-JUN-12
    SQL> SY.

  • Difference between two dates: a complete solution

    There have been many posts asking how to get the number of days between two dates. There is no method in java like the VB method dateDiff(), and there is only the method date.getTime() which gives you the number of milliseconds since Jan 1 1970, the Epoch. I have not seen a solution that makes use of the fact that there are 86400000 milliseconds per day, only when trying to get the number of days , i.e. multiples of 24 hours between two millisecond points in time.
    So what if date1 was Oct 26th 11.30pm and date2 was Oct 27th 12.30am? If you get the millisecond difference, and divide by 86400000, you do not notice that these two times are on separate days, but only one hour apart.
    My solution takes account of the modulo (%) function. If you use the date.getTime() method, and use % 86400000 on this number of milliseconds, it will tell you how far (milliseconds) this date is into this day, after 12am. If you subtract this amount from the total number of milliseconds, then divide by 86400000, this will give you the number of days after the Epoch, so you are able to know which day the millisecond time is in. If you want to know the days between two millisecond times, this will tell you, whereas just dividing by 86400000, will not, and may be misleading.
    I think this could be incorporated into the Date class easily. There are some problems though, as not every day has 86400000 milliseconds, if you are talking about days when Daylight Saying Time begins or ends. Doing calculations like that will create errors, unless you know whether each date is in Daylight Saving Time or not. Leap years are OK, unless want to work out the number of years from the number of days by dividing by 365, as calculating numbers of days is only done by looking at a 24 hour time period. However where 'leap seconds' have been added, like once every ten years, there may be small errors. This was not included in anyone elses calculations.
    So the calculation would go like this:
    public class BetterDate extends Date
    public int dayDifference(Date d)
    long time = this.getTime() ; // gets milliseconds
    long timed = d.getTime() ; // gets milliseconds of other date
    int days = (time - (time % 86400000))/86400000 ; // number of days
    int daysd = (timed - (timed % 86400000))/86400000 ; // number of days of other date
    int difference = daysd - days ; // difference in days between two dates
    return difference ;
    If you want you can use the value (time % 86400000), and modulo this amount with the number of milliseconds in one hour, then subtract the result from the (time % 86400000) and divide by the millliseconds in one hour to give you the number of hours, but there are JDK functions that you can use to get the hour if needed.
    This method is not perfect, but for most cases will get you the difference in days between two dates.
    James

    Hi James,
    I tried out your solution, but it seems to fail on dates without times. I tries the difference between 31/03/2002 and 01/04/2002 and the result is 0. I guess it is because the times are assumed to be 00:00 as no times are mentioned and 31st March I believe is the date when DST change will take place this year. If I set the two times as well to a time much later than midnight for example 0600 then I seem to get the right answer.
    Joag
    There have been many posts asking how to get the
    number of days between two dates. There is no method
    in java like the VB method dateDiff(), and there is
    only the method date.getTime() which gives you the
    number of milliseconds since Jan 1 1970, the Epoch. I
    have not seen a solution that makes use of the fact
    that there are 86400000 milliseconds per day, only
    when trying to get the number of days , i.e. multiples
    of 24 hours between two millisecond points in time.
    So what if date1 was Oct 26th 11.30pm and date2 was
    Oct 27th 12.30am? If you get the millisecond
    difference, and divide by 86400000, you do not notice
    that these two times are on separate days, but only
    one hour apart.
    My solution takes account of the modulo (%) function.
    If you use the date.getTime() method, and use %
    86400000 on this number of milliseconds, it will tell
    you how far (milliseconds) this date is into this day,
    after 12am. If you subtract this amount from the total
    number of milliseconds, then divide by 86400000, this
    will give you the number of days after the Epoch, so
    you are able to know which day the millisecond time is
    in. If you want to know the days between two
    millisecond times, this will tell you, whereas just
    dividing by 86400000, will not, and may be
    misleading.
    I think this could be incorporated into the Date class
    easily. There are some problems though, as not every
    day has 86400000 milliseconds, if you are talking
    about days when Daylight Saying Time begins or ends.
    Doing calculations like that will create errors,
    unless you know whether each date is in Daylight
    Saving Time or not. Leap years are OK, unless want to
    work out the number of years from the number of days
    by dividing by 365, as calculating numbers of days is
    only done by looking at a 24 hour time period. However
    where 'leap seconds' have been added, like once every
    ten years, there may be small errors. This was not
    included in anyone elses calculations.
    So the calculation would go like this:
    public class BetterDate extends Date
    public int dayDifference(Date d)
    long time = this.getTime() ; // gets milliseconds
    long timed = d.getTime() ; // gets milliseconds of
    other date
    int days = (time - (time % 86400000))/86400000 ; //
    number of days
    int daysd = (timed - (timed % 86400000))/86400000 ; //
    number of days of other date
    int difference = daysd - days ; // difference in days
    between two dates
    return difference ;
    If you want you can use the value (time % 86400000),
    and modulo this amount with the number of milliseconds
    in one hour, then subtract the result from the (time %
    86400000) and divide by the millliseconds in one hour
    to give you the number of hours, but there are JDK
    functions that you can use to get the hour if needed.
    This method is not perfect, but for most cases will
    get you the difference in days between two dates.
    James

  • Difference between Two Date Should come into Text Item

    Dear All,
    i want to get difference between two date into text Item :P36_C in On Change java script.
    i have two Date Item :P36_A and :P36_B .i have extract these date value from table then difference comes into Text Field :P36_C.
    Now i want if i change Date into Item :P36_A or Item :P36_B then Defference between two date Should Come into Item :P36_C .
    So i have use Java Script Code to do this
    <script>
      function diffdat(){
        function getVal(item){
       if($x(item).value != "")
         return parseFloat($x(item).value);
       else
         return 0;
        $x('P36_C').value =
    getval((TO_DATE('P36_B', 'DD-MON-YYYY'))-
    getval(TO_DATE('P36_A', 'DD-MON-YYYY')))+1;
    </script>
    i have put this into Item HTML Form Element Attributes 
    onChange="javascript:diffdat();"it's not woring .
    How to work that Code with dates.
    Thanks

    You can always create your own difference function based on your own criteria. You can modify this to suit your needs.
    CREATE OR REPLACE FUNCTION CALC_OFFICE_DAYS(date1 DATE, date2 DATE)
    RETURN NUMBER
    IS
    v_begin_date DATE := date1;
    v_end_date DATE := date2;
    v_office_start_time VARCHAR2(10) := '09:30 AM';
    v_office_end_time VARCHAR2(10) := '06:30 PM';
    v_comp_begin_time DATE;
    v_comp_end_time DATE;
    v_days PLS_INTEGER := 0;
    v_hrs NUMBER := 0;
    v_ttltm NUMBER;
    BEGIN
    select trunc(v_end_date) - trunc(v_begin_date)
    into v_days
    from dual;
    select to_date(to_char(sysdate,'DD-MM-YYYY')||' '||to_char(v_begin_date,'HH24:MI'),'DD-MM-YYYY HH24:MI')
    into v_comp_begin_time
    from dual;
    select to_date(to_char(sysdate,'DD-MM-YYYY')||' '||to_char(v_end_date,'HH24:MI'),'DD-MM-YYYY HH24:MI')
    into v_comp_end_time
    from dual;
    select (v_comp_end_time - v_comp_begin_time)/24 into v_hrs from dual;
    IF v_hrs > 4 then
    v_ttltm := v_days + .5;
    ELSE
    v_ttltm := v_days;
    END IF;
    return v_ttltm;
    END;
    As has been noted, this question is best posted on the PL/SQL forum.

  • Difference between two dates in hours

    hi
    i want to write the procedure which will give me the difference of two dates in hours.
    there are two columns start_dt and end_dt and i want to calculate the difference between them in hours.
    morever i want to add functionality like if the start or end date falls on weekend(saturday & sunday) i want to subtract that whole period(which obviously will be in hours) from the total hours elapsed between two dates.
    could anyone please help me in this?
    regards,
    PD

    nicolas..
    thanks for bringing this into my notice..
    i used ur one of the reply..
    select
    to_char(sysdate,'dd-mm-yyyy hh:mi:ss') d1,
    to_char(sysdate-45.4,'dd-mm-yyyy hh:mi:ss') d2,
    trunc(sysdate-(sysdate-45.4)) "Days",
    trunc(((sysdate-(sysdate-45.4))-trunc(sysdate-(sysdate-45.4)))*24) "Hours",
    trunc(((((sysdate-(sysdate-45.4))-trunc(sysdate-(sysdate-45.4)))*24)-trunc(((sysdate-(sysdate-45.4))-trunc(sysdate-(sysdate
    -45.4)))*24))*60) "Minutes",
    trunc((((((sysdate-(sysdate-45.4))-trunc(sysdate-(sysdate-45.4)))*24)-trunc(((sysdate-(sysdate-45.4))-trunc(sysdate-(sysdat
    e-45.4)))*24))*60)-trunc(((((sysdate-(sysdate-45.4))-trunc(sysdate-(sysdate-45.4)))*24)-trunc(((sysdate-(sysdate-45.4))-tru
    nc(sysdate-(sysdate-45.4)))*24))*60)) "Second"
    from dual
    it's working but the problem is that i also have to give functionality like if the start_dt or end_dt is on holiday(i.e. weekend or holiday) i need to subtract the hours spent during holiday period from total hours.
    any help?
    regards,
    PD!!

  • Date difference between two dates

    hi All,
    i have to right a stored proc to find the difference between two dates. 
    for example of i give
    startdate as 4/1/2015 and enddate 14/1/2015
    i should get 1 year , 10 days and 0 months .
    i have tried the DateDiff function but it does not calculate the leap year.
    please help.

    DECLARE @from datetime
    DECLARE @to   datetime
    SET @from = '20150104  8:00'
    SET @to   = '20150114  10:30'
    SELECT DATEDIFF(minute,@from, @to) % 60 as Minutes
    SELECT (DATEDIFF(minute,@from, @to) / 60) % 24 as Hours
    SELECT DATEDIFF(minute,@from, @to) / (60 * 24) as Days
    SELECT DATEDIFF(month,@from, @to) as Months
    SELECT DATEDIFF(year,@from, @to) as Year
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Difference between two dates into server behaviors

    Good morning all,
    I'm trying to create a recordset using server behaviors and as I'm not an expert using php I'm completely lost...
    The problem is the following : I want to find into a table all the records where the difference between today date and their creation date (stored in that table of course) is greater than, let's say 30days. How can I indicate that into the variables field ?
    Many thanks in advance for your help !

    Many thanks !
    I was ignoring the DATE_SUB function and it does work in such a simple way… (with a closing parenthesis at the end)
    Thanks again !
    Best regards
    De : osgood_ [email protected]
    Envoyé : lundi 16 septembre 2013 15:59
    À : Berurier75
    Objet : Difference between two dates into server behaviors
    Re: Difference between two dates into server behaviors
    created by osgood_ <http://forums.adobe.com/people/osgood_>  in Dreamweaver support forum - View the full discussion <http://forums.adobe.com/message/5685549#5685549

  • How to get the difference between two date

    Hello,
    I want to know how to write a code the tell me the difference between two date, I am using
    oracle.jbo.domain.Date
    i have a rent date and return date so my code is
    Date rent=(Date)nr.getAttrbute("RentDate"),ret=(Date)nr.getAttrbute("ReturnDate");
    is there a way to know the difference in days between those two dates ?
    Thanks

    hi,
    try this.....
    DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
    Date date = (Date)formatter.parse(dateStr); //// dateStr <- from date value (that is string value)
    Date dateto = (Date)formatter.parse(datetostr); //// datetostr <- to date value (to date getting from as a string)
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    Calendar calto = Calendar.getInstance();
    calto.setTime(dateto);
    fromDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
    toDate = calto.get(Calendar.DATE) + "/" + (calto.get(Calendar.MONTH) + 1) + "/" + calto.get(Calendar.YEAR);
    // System.out.println("from Date : " + fromDate);
    if ((fromDate != null && toDate != null) && (date.compareTo(dateto) > -1) ) {                  
    fc.addMessage("VacationQueryComponent", new FacesMessage(FacesMessage.SEVERITY_ERROR, "From Date cannot be lower than To Date", "From Date cannot be lower than To Date"));
    fc.renderResponse();
    thks.

  • Calculate difference between two dates/times

    Hi all,
    Is there any function module to calculate difference between two dates/times which are in TIMESTAMPL format.
    I need to know how many millisconde(second,minutes, hours... )there is between these two times.
    Please, It is urgent
    Thank you all.
    Karim

    hi,
    try the following function
    CALL FUNCTION 'CCU_TIMESTAMP_DIFFERENCE'        
          EXPORTING                                  
               timestamp1 = timestamp1               
               timestamp2 = timestamp2               
          IMPORTING                                  
               difference = diff                     
          EXCEPTIONS                                 
               OTHERS     = 1. 
    the above function gives the difference in seconds...
    try the following  code to set the resolution to milliseconds..
    SET RUN TIME CLOCK RESOLUTION LOW
    check the thread for details:
    SET RUN TIME CLOCK RESOLUTION?
    all the best!!!
    Regards,
    Aparna

  • Calculate the difference between two dates

    I would like to calculate the difference between two dates in PL/SQL and return the result as a number of days expressed as an integer value.

    Denes,
    A fair point, I should really have posted this on the SQL forum (I'm new to the forum as well as PL/SQL) but thanks for responding anyway. It does raise a question as to how to implement this in ApEx though.
    I have created the function and am calling it as shown below from the source window of a form. The source type is 'PL/SQL expression or function' and the expression in the source window of the form is:
    calc_date_difference (:p26_c_payment, :p26_c_rec)
    The two parameters being passed are of type date but I'm not sure how to handle the ruturned number and populate the form in ApEx with this value.
    Is it possible to do it this way or am I taking completely the wrong approach?
    Regards
    Sandy
    This is not ApEx related but SQL related:
    CREATE OR REPLACE FUNCTION calc_date_difference (
    p_date_1   VARCHAR2,
    p_date_2   VARCHAR2
    RETURN NUMBER
    v_difference   NUMBER;
    v_sql_err      VARCHAR2 (4000);
    BEGIN
    v_difference := TRUNC (TO_DATE (p_date_1)) - TRUNC
    (TO_DATE (p_date_2));
    RETURN v_difference;
    CEPTION
    WHEN OTHERS
    THEN
    v_sql_err := SQLERRM || CHR (10) || CHR (10) ||
    SQLCODE;
    ND calc_date_difference;and
    SQL> SELECT calc_date_difference ('23.01.2007',
    '20.01.2007') diff
    2    FROM DUAL;
    DIFF
    3
    Denes Kubicek                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How to calculate the month difference between two date char. in Query?

    Customers would like to see how many months passed between two date type of characteristics (e.g., the month difference between the current date and the scheduled delivery date in the record) and put the result into the column as KF. 
    We would have to grab the fiscal year/period kind of value and then do the subtraction, e.g., if the current date value is 2/28/2008 and the scheduled delivery date value in the record is 12/01/2007, the correct result should be 2 month difference between these two date values, but could someone here give us the technical light on how to make this happen in query design?
    Thanks and we will give you reward points for the correct anwsers!

    Hi Kevin,
    The Badi is RSR_OLAP_BADI.
    You can create an implementation using Transaction  SE18.
    The implementation is per cube and is defined in the filters.
    In the Implementation you have the following methods :
    1. Define : Here you will provide the Keyfigure you need as a virtual one.
    2. Initilialize : Any Init Function you want to do.
    3. Compute. This is called per datarecord and here you can cimpute your value.
    Hope this helps.
    Pralay Ahluwalia

  • As to the data type of the data type of the difference between two date type of datas

    Hi,
    I have a question about the data type of the difference between two date type of datas.
    There are two date type of datas as:
    SSHIPMENTS.RECEIVEDATETIME
    SSHIPMENTS.PROMISEDATETIME
    I try to use the following SQL Script in Oracle SQL*Plus as:
    SELECT CASE
    WHEN (SSHIPMENTS.RECEIVEDATETIME - SSHIPMENTS.PROMISEDATETIME) < '000 01:00:00.000' THEN 'OnTime'
    WHEN (SSHIPMENTS.RECEIVEDATETIME - SSHIPMENTS.PROMISEDATETIME) < '000 01:30:00.000' THEN '60-89 Minutes'
    ELSE '3+ Hours'
    END
    FROM SSHIPMENTS;
    The error message of "Invalid Number" for the '000 01:30:00.000' happens.
    I don't know if the data type of the interval is wrong.
    Many Thanks,
    Cathy

    SELECT CASE
    WHEN (to_char(SSHIPMENTS.RECEIVEDATETIME,'hhmiss') - to_char(SSHIPMENTS.PROMISEDATETIME,'hh24miss')) < '010000' THEN 'OnTime'
    WHEN (to_char(SSHIPMENTS.RECEIVEDATETIME,'hhmiss') - to_char(SSHIPMENTS.PROMISEDATETIME,'hh24miss'))< '000 01:30:00.000' THEN '60-89 Minutes'
    ELSE '3+ Hours'
    END
    FROM SSHIPMENTS;
    just try it out..

  • Difference between two date in bex query

    Hi all,
    I need to do a difference between two date using formula variable processing type customer exit beaucause I must use factory calendar in the formula.
    How can I do it?
    Can you give me an example of the routine?
    Thanks a lot
    Gianmarco

    Hi,
    You can still use the same code to copy it and customize as per your need. All you need to do is to subract the dates using the class: CL_ABAP_TSTMP after converting to timestamp and resulting seconds you convert back to days....Please get help from the developers to do this...
    Also, ensure that you write back this difference value to your variable so you get it on the reports for your calculations...
    Cheers,
    Emmanuel.

Maybe you are looking for