Find Exact number of days between two dates

How can get the exact number of days between two dates?

An example of business days calculation in SQL */
/* The algorythm is: */
/* 1) Take the absolute difference between the dates */
/* to_date('&todate') - to_date('&frdate') */
/* 2) Subtract the weekends (number of weeks in the range */
/* TRUNC(to_date('&todate'),'D') = 1st day of week that */
/* end of period is in */
/* TRUNC(to_date('&frdate'),'D') = Last day of week that */
/* start of period is in */
/* So subtracting these two gives the number of days */
/* between the two dates but including all of the days in */
/* the weeks that the dates start and end in. When this */
/* number is divided by 7 it gives the number of weeks. */
/* Multiplying by 2 gives the number of weekend days.     */
/* 3) Subtract 1 day if the ending date is on a saturday */
/* DECODE(to_char(to_date('&todate'),'D'),7,-1,0) */
/* --> If the day of the week is saturday (7), returns -1 */
/* 4) Subtract 1 day if the start date is on a sunday */
/* DECODE(to_char(to_date('&frdate'),'D'),1,-1) */
/* --> If the day of the week is sunday (1), returns 1 */
/* 5) Add one day to make the range inclusive (The '1 + ' ) */
/* Author: Kenneth Atkins ([email protected]) */
/* http://www.olywa.net/katkins/oratip */
define frdate = '&1'
define todate = '&2'
set verify off
select      
     '&frdate' From_Date
     ,'&todate' To_Date,
     1 + to_date('&todate') - to_date('&frdate') -
     ((TRUNC(to_date('&todate'),'D') - TRUNC(to_date('&frdate'),'D'))/7)*2
     + DECODE(to_char(to_date('&todate'),'D'),7,-1,0)
+ DECODE(to_char(to_date('&frdate'),'D'),1,-1,0) Business_Days
from dual
Here is an example of running the script:
SQL> @busdays 01-AUG-96 15-AUG-96
FROM_DATE TO_DATE BUSINESS_DAYS
01-AUG-96 15-AUG-96 11

Similar Messages

  • Number of days between two dates

    I have two dates-String Date1, String Date2(format of both the dates is 'DD-MM-YY'eg;'28-Jan-2008'). I want to find the difference between these dates;ie if value of String Date1 is '28-Jan-2008' and value of String Date2 is '28-Jan-2009', I need to find the number of days between these dates. What need to be done? Can anyone help me out please.
    Thanks in advance for all the help.
    Regards,
    Anees

    Doing a search is a bit ineffiecient. I'd take advantage of the fact that dates are acually stored in milliseconds. Subtract the two millisecond values (Data.getTime()) and divide by the number of milliseconds in a day. One complication, though, is daylight saving time but if you round rather than truncate in the division it should be fine.
    private static final long MILLIS_PER_DAY = 24L * 60L * 60L * 1000L;
    int dayDiff = (int)((date2.getTime() - date1.getTime() + MILLIS_PER_DAY/2)  / MILLIS_PER_DAY);

  • How can i get number of days between two dates represented by two dates?

    how can i get number of days between two dates represented by two date objects. One is java.sql.Date, the other is java.util.Date?

    tej_222 wrote:
    But how do I do that conversion. from java.sql.date and java.util.date to calender?
    -thanks for the quick response.You may find the following utility code samples useful:
    [http://balusc.blogspot.com/2007/09/calendarutil.html]
    [http://balusc.blogspot.com/2007/09/dateutil.html]
    ganeshmb wrote:
    (date1.getTime() - date2.getTime())/(1000*60*60*24) should do.
    getTime returns millsecond value of date object and the difference divided by no of milliseconds in a day should fetch you the difference in terms of days.This doesn't respect the DST. Use java.util.Calendar.

  • I wanted to know how do you calculate the number of days between two dates

    i wanted to know how do you calculate the number of days between two dates in java ? i get both the dates from the database. i guess there are many issues like leap year and Febuary having diff no of months ..etc.

    thanks..
    I solve my problem as
    public class MyExample {
        public static void main(String a[]) {
            String stdate = "2009-03-01";
            java.sql.Date currentDate = new java.sql.Date(System.currentTimeMillis());
            java.sql.Date preDate = java.sql.Date.valueOf(stdate);
            System.out.println(currentDate);
            System.out.println(preDate);
    //        int dateCom = preDate.compareTo(currentDate);
    //        System.out.println(dateCom);
            long diff = currentDate.getTime() - preDate.getTime();
            int days = (int) Math.floor(diff / (24 * 60 * 60 * 1000));
             System.out.println(days);
    }

  • How can I calculate the maximum number of days between two dates in a range of dates?

    I have a column of dates spanning the couse of a few months.  I would like to know if I can calculate the maximum number of days between each row and display the highest number.  I currently have another column that calculates the days betwen the rows and I am currently just looking at the totals and highlighting the highest period.
    Is this possible?  Any help or suggestions are appreciated.
    Thank you,
    Trevor

    This sounds totally possible,  Can you post a screen shot of your table to make responding more focused?  If you mean you want to:
    A) compute the difference (in days) between two date in the same row, then
    B) find the max duration (in days)
    Here is my take on this problem:
    D2 = C2-B2
    select D2 and fill down
    F1=MAX(D)
    to perform the conditional formatting (to highlight the max duration) select column D, then set up conditional formatting as shown in the 1st image

  • How to calculate number of days between two date in Template design?

    Hello guys
    I have a situation where I have to create a template that returns data, and one of the thing of the existing report is that there is a column that is actually the number of days between start date and end date columns..
    So in template, how would I be able to do the same? I have start date and end date columns on the template, now when I created another column using expression like end date - start date and preview the template, I am getting errors saying :
    Caused by: oracle.xdo.parser.v2.XPathException: Cannot convert 03/31/2009 to number.
         at oracle.xdo.parser.v2.XSLStylesheet.flushErrors(XSLStylesheet.java:1534)
         at oracle.xdo.parser.v2.XSLStylesheet.execute(XSLStylesheet.java:521)
         at oracle.xdo.parser.v2.XSLStylesheet.execute(XSLStylesheet.java:489)
         at oracle.xdo.parser.v2.XSLProcessor.processXSL(XSLProcessor.java:271)
         at oracle.xdo.parser.v2.XSLProcessor.processXSL(XSLProcessor.java:155)
         at oracle.xdo.parser.v2.XSLProcessor.processXSL(XSLProcessor.java:192)
    Please advice
    Thanks

    Hi
    There is an extension function you can use, from the javadoc:
    date_diff
    public static long date_diff(java.lang.String format,
    java.lang.String fromDate,
    java.lang.String toDate,
    java.lang.String locStr,
    java.lang.String tzID)
    Method to get the difference between two dates in the given locale. The dates need to be in "yyyy-MM-dd" format. This function supports only Gregorian calendar.
    Parameters:
    format - the format to which the difference is required; allowed formats are y (for Year), m(for month), w(for week), d(for day), h(for hour), mi(for minute), s(for seconds) and ms(for milliseconds)
    fromDate - the first date
    toDate - the second date
    locStr - locale string -> lang-Territory
    tzID - timezone ID ->http://java.sun.com/j2se/1.4.2/docs/api/java/util/TimeZone.html
    Returns:
    the difference in dates in the desired format
    For example
    <?xdoxslt:date_diff(‘d’,’2009-09-14’, ‘2009-09-20’,’en-US’,1)?>
    give a result of 6
    You can substitute in columns for the dates, just remember the date format required.
    Regards
    Tim

  • SQL to count the number of days between two dates

    Does any one have or know how to count the number of days/weeks between 2 dates.
    I have thought about using MONTHS_BETWEEN, but do not know how to make it accurate down to one day?
    Any suggestions would be appreciated.

    here are the different queries I came up with to do this, you may want to check it for perticular cases involving Sun and Sat as start and end dates.
    select to_number(to_char(to_date('21-JUL-00','dd-mon-yy'), 'ww'))
    - to_number(to_char(to_date('10-JUL-00','dd-mon-yy'), 'ww')) from dual;
    select (Next_Day(to_date('21-JUL-00','dd-mon-yy')-1, 'Sunday')
    - Next_Day(to_date('10-JUL-00','dd-mon-yy')-1, 'Sunday'))/7 from dual;
    select (Next_Day(to_date('21-JUL-00','dd-mon-yy')-6, 'Sunday')
    - Next_Day(to_date('10-JUL-00','dd-mon-yy')-6, 'Sunday'))/7 from dual;
    null

  • Number of days between to dates

    Hello to all,
    I would like to define a formula to calculate number of days between two dates and update the value in a key figure.
    *operand: {Name of keyfigure,Fecha ini (Mes/Año),Fecha Fin (Mes/Año)}
    DATA FECHAINI  TYPE ZIOV_FEIN.
    DATA FECHAFIN TYPE ZIOV_FFIM.
    DATA INI             TYPE 0CALMONTH.
    DATA FIN            TYPE 0CALMONTH.
    DATA DIA_INI      TYPE D.
    DATA DIA_FIN     TYPE D.
    DATA DIAS          TYPE F.
    FOREACH FECHAINI, FECHAFIN.
      INI = FECHAINI.
      FIN = FECHAFIN.
    *C2DATE Determine end period date
      DIA_INI = C2DATE(INI, E).
      DIA_FIN = C2DATE(FIN, E).
      DIAS = DIA_FIN - DIA_INI.
    {ZIOV_DIAS,FECHAINI,FECHAFIN} = DIAS.
    ENDFOR.
    Problem: UPF057 type F conflicts with type D. 
    Help would be much appreciated.
    Regards,
    Patrícia

    The function is built in:
    CALL METHOD CL_RSAR_FUNCTION=>DATE_DIFF(
      EXPORTING I_DATE_1 = L_ARG2
                I_DATE_2 = L_ARG3
      IMPORTING E_RESULT = L_ARG1  )

  • How to query the number of working days between two dates

    I'm looking for a solution to calculate the number of <i>working</i> days between two dates that I can use in a formated search. 
    Calculating the total number of days is pretty straight forward but does anyone know how to take into account the settings in the HLD1 (Holiday Dates) table?

    Hi Eric,
    If you are purely looking to exclude holidays defined in the HLD1 table, then you should be able to do it with the following query
    NOTE: The following query is an example using OINV table and the fields DOCDATE and DOCDUEDATE for a Particular DOCNUM  'xxx'
    If you planning to use within the SAP module then replace DOCDATE and DOCDUEDATE with dynamic field references $[$x.x.x]
    SELECT DATEDIFF(DAY,T0.DOCDATE,T0.DOCDUEDATE)-
    (SELECT COUNT(STRDATE) FROM HLD1 WHERE STRDATE >= T0.DOCDATE AND STRDATE <= T0.DOCDUEDATE)
    FROM OINV T0
    WHERE T0.DOCNUM = xxx
    Best Wishes
    Suda

  • Number of occurences between two dates based on a starting date + frequence

    I have a starting date in cell A1 and a frequency (in days) in cell B1. In cell C1 I have a date (begin) and in cell C4 I have a later date (end). I need to know how often the event occurs during the time between begin and end dates (inclusive).
    For instance, the starting date is january 25th, the frequency is 5. The first date is januari 25th, the second date is februari 12th. The result should be 2 (because given the starting date and frequency of the event, it will occur in februari on day 4 and 9).
    I have been looking at some of the statistical functions, but I don't think there is a function for this. Right now I have about 5 formulas to calculate intermediate results, but I'm stuck trying to combine them.
    I would be happy with just a pointer in the right direction. For instance, is there a specific name for this kind of calculation?

    michielvoo wrote:
    I have a starting date in cell A1 and a frequency (in days) in cell B1. In cell C1 I have a date (begin) and in cell C4 I have a later date (end). I need to know how often the event occurs during the time between begin and end dates (inclusive).
    For instance, the starting date is january 25th, the frequency is 5. The first date is januari 25th, the second date is februari 12th. The result should be 2 (because given the starting date and frequency of the event, it will occur in februari on day 4 and 9).
    If the event occurs every five days, the second date will be January 30, and the event will occur four times " during the time between begin and end dates (inclusive)"
    I have been looking at some of the statistical functions, but I don't think there is a function for this. Right now I have about 5 formulas to calculate intermediate results, but I'm stuck trying to combine them.
    It's not really a statistical calculation, but a simple division to find "How many whole sets of five (days) are there in the days between two dates."
    I would be happy with just a pointer in the right direction. For instance, is there a specific name for this kind of calculation?
    Two functions and one operation are needed:
    DATEDIF() to calculate the number of days between the start and end dates.
    Division to determine how many sets of five days there are in that period.
    INT() to discard the fractional part of the result.
    With the values located as described, this formula (placed in a cell on the same table) will return the number of occurrences not including the first one.
    =INT(DATEDIF(C1,C4,"D")/B1)
    To include the Start date as one of the occurrences, make this modification:
    =INT(DATEDIF(C1,C4,"D")/B1)+1
    Regards,
    Barry

  • Calculation of MONTHS , YEARS , & DAYS between two dates

    Hi Experts,
      Currently i am using this functional Module. which calculates the number of months between two dates.
       CALL FUNCTION 'FIMA_DAYS_AND_MONTHS_AND_YEARS'
             EXPORTING
                  I_DATE_FROM = ITAB_PER-BEGDA
                  I_DATE_TO   = ITAB_PER-ENDDA
             IMPORTING
                  E_MONTHS    = CMONTHS.
      BUT this functional module Rounding off the Month...Say ..if the total numbr of days between from & to date is 105 it is showing as 4 months ...
      <b>Is there any other Functional Module</b> ????which Calculates the EXACT MONTH between two dates...(in the above case the month is expected to be 3 only since it is 105 days only)..
      Kindly help me regarding this....

    lakshimiraja,
    You can use this function module.
    report zrich_0003
           no standard page heading.
    data: duration_in_months type i.
    parameters: s_date type sy-datum,
                e_date type sy-datum.
    call function 'DURATION_DETERMINE'
    exporting
       unit                             = 'MON'
       factory_calendar                 = 'P6'    "  Your factory calendar
    importing
       duration                         = duration_in_months
    changing
       start_date                       = s_date
       end_date                         = e_date
    exceptions
       factory_calendar_not_found       = 1
       date_out_of_calendar_range       = 2
       date_not_valid                   = 3
       unit_conversion_error            = 4
       si_unit_missing                  = 5
       parameters_not_valid             = 6
       others                           = 7.
       write:/ duration_in_months.
    Don't forget to reward if useful...

  • Number of days between 2 dates

    HI,
    I am working on a program that needs to show number of days between 2 dates. When I scanned the function library, I only found a function to give you the number of years between dates. I can probably code this in ABAP but does anyone know if a function exists to do this.

    Hi  Suneela
    Are you concern with the normal dates or do you have any concern with the Factory dates ?
    Lets take both
    1) Normal dates
    It seems that you are trying to get the days between two dates , That you can simply get by subtracting one from the other or else by .
    Assuming that you populated the dates just after the declaration .
    Sample code
                  Data : date1 like sy-datum,
                             Date2 like sy-datum ,
                             No_of_days type i.
                  No_of_days =  date1 – date2.
    Or Else the FM
         Days_between_two_dates
      Sample code
       Data : date1 like sy-datum,
                             Date2 like sy-datum ,
                             No_of_days type i.
    Call function ‘days_between_two_dates’
      Exporting
        I_datum_bis   = Date2   “ Second date
        I_datum_von = date1    “ Start date
    Importing
         E_tage = No_of_days
    Exceptions
      Days_method_not_defined = 1
      Others = 2.
    2) Factory dates
    If You want to find out the difference based on factory calendar
    Then convert the dates to factory calendar dates  first and then simply subtract those factory calendar dates to get  offset days based on factory calendar.
    *Sample code *
       Data : date1 like sy-datum,
                             Date2 like sy-datum ,
                             No_of_days type i.
    data: l_fac_date like  SCAL-FACDATE ,   " Factory calendar: Factory
          l_fac_date2 like SCAL-FACDATE,
          l_fac_date1  like SCAL-FACDATE.
    Perform get_factory_date using date1
                             Changing l_fac_date1.
    Form get_factory_date using l_date
                             Changing l_l_fac_date.
    IF NOT l_date1 IS INITIAL.
       CALL FUNCTION 'DATE_CONVERT_TO_FACTORYDATE'
         EXPORTING
      CORRECT_OPTION                     = '+'
           DATE                               = l_date
           FACTORY_CALENDAR_ID                = 'AU' "
        IMPORTING
      DATE                               =
         FACTORYDATE                        = l_l_fac_date
      WORKINGDAY_INDICATOR               =
      EXCEPTIONS
          CALENDAR_BUFFER_NOT_LOADABLE       = 1
           CORRECT_OPTION_INVALID             = 2
           DATE_AFTER_RANGE                   = 3
           DATE_BEFORE_RANGE                  = 4
           DATE_INVALID                       = 5
           FACTORY_CALENDAR_NOT_FOUND         = 6
           OTHERS                             = 7
       IF SY-SUBRC <> 0.
         MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                 WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
       ENDIF.
    ENDIF.
    Endform.
    Move l_fac_date to l_fac_date1.
    *Do the same for the second date also i.e  . 
    Perform get_factory_date using date2
                             Changing l_fac_date2.
    No_of_days = l_fac_date1 - l_fac_date2.
    Hope this will help you.
    Reward points if helpful

  • How to Calculate number of months between two dates

    Hi All,
       In one of the fomr developments, I have to calculate the
    Number of Days
    Number of Months ( Considering Leap Year) provided by the dates, end user enters in the form,
    After going thorugh some forum discussion, I have come to know about so many things which were not clear till now.
    I have gone through various forums too,  some one suggets to make use of FORM CALC and some other JAVA SCRIPT. But the logic i want to build in java script.
    The most interesting point is the DATE object is not getting created when i write  the below code
      var startDate = new DATE(oYear, oMonth, oDay);
    I am still not clear, that really the date object gets created in Adobe form If so the why the alert box is getting populated when i write below lines
    var oTemp = startDate.getFullYear();
    xfa.host.messagebox(oTemp);
    So, there are so many unclear things,
    If any one can help me by suggesting the approach and how to build the logic in the JavaScript I would be really thankful
    Regards
    PavanChand

    Hi,
    ChakravarthyDBA wrote:
    Hi
    I want number of Sundays between two dates
    example
    number of Sundays count between '01-04-2013' and '30-04-2013' in one select query I have to include this as sub query in my select statement.Here's one way:
    SELECT       early_date
    ,       late_date
    ,       ( TRUNC (late_date + 1, 'IW')
           - TRUNC (early_date,        'IW')
           ) / 7       AS sundays
    FROM       table_x
    ;This does not depend on your NLS settings.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and also post the results you want from that data.
    Point out where the statment above is getting the wrong results, and explain, using specific examples, how you get the right results from the given data in those places.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}

  • How to calculate days between two DATES

    How to calculate days between two DATES ?
    which is the functional module for that ?
    help me

    Hi,
    use function module : it works,
    HR_HK_DIFF_BT_2_DATES
    give output format = 03 and get the value in days.
    code is as below :
    data : DATE1 type P0001-BEGDA,
    DATE2 type P0001-BEGDA,
    YEARS type P0347-SCRYY,
    MONTHS type P0347-SCRMM,
    DAYS type P0347-SCRDD.
    date1 = '20070331'.
    date2 = '20070101'.
    CALL FUNCTION 'HR_HK_DIFF_BT_2_DATES'
    EXPORTING
    DATE1 = date1
    DATE2 = date2
    OUTPUT_FORMAT = '03'
    IMPORTING
    YEARS = years
    MONTHS = months
    DAYS = days
    EXCEPTIONS
    INVALID_DATES_SPECIFIED = 1
    OTHERS = 2
    IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    write : days.
    Reward points, if helpful,
    Regards,
    Sandeep Kaushik

  • Calculate business day between two dates

    Hi Guys
    I need the count of business days between two  dates
    Date1, Date2 i need the count only business day (exclude sartuday&sunday)
    If date1 is null or nothing i need to pass 0
    If date2 is null or nothing i need to pass 0
    help on this

    Hi,
    To achive this within SSRS, go to the report code window and add the below
    Function getBusinessDaysCount(ByVal tFrom As Date, ByVal tTo As Date) As Integer
    Dim tCount As Integer
    Dim tProcessDate As Date = tFrom
    For x as Integer= 1 To DateDiff(DateInterval.Day, tFrom, tTo) + 1
    If Not (tProcessDate.DayOfWeek = DayOfWeek.Saturday Or tProcessDate.DayOfWeek = DayOfWeek.Sunday) Then
    tCount = tCount + 1
    End If
    tProcessDate = DateAdd(DateInterval.Day, 1, tProcessDate)
    Next
    Return tCount
    End Function
    In the textbox where you need to display the value, add the below expression
    =Code.getBusinessDaysCount(parameters!StartDate.Value,parameters!EndDate.Value)
    It is assumed the you want to pass the two days from parameters named Startdate and EndDate. If not, modify the expression with required values.
    Regards
    Please click "Mark as Answer" if this resolves your problem or "Vote as Helpful" if you find it helpful. BH

Maybe you are looking for