How to get the difference of two dates in years,months and days

Hi friends,
how to get the difference of two dates in years,months and days
for ex 2 years 3 months 13 days
select (sysdate-date_Start) from per_periods_of_service
thanks

Something like this...
SQL> ed
Wrote file afiedt.buf
  1  with t as (select to_date('17-nov-2006','dd-mon-yyyy') as c_start_date, to_date('21-jan-2008','dd-mon-yyyy') as c_end_date from dual union all
  2             select to_date('21-nov-2006','dd-mon-yyyy'), to_date('17-feb-2008','dd-mon-yyyy') from dual union all
  3             select to_date('21-jun-2006','dd-mon-yyyy'), to_date('17-jul-2008','dd-mon-yyyy') from dual
  4             )
  5  -- end of test data
  6  select c_start_date, c_end_date
  7        ,trunc(months_between(c_end_date, c_start_date) / 12) as yrs
  8        ,trunc(mod(months_between(c_end_date, c_start_date), 12)) as mnths
  9        ,trunc(c_end_date - add_months(c_start_date, trunc(months_between(c_end_date, c_start_date)))) as dys
10* from t
SQL> /
C_START_D C_END_DAT        YRS      MNTHS        DYS
17-NOV-06 21-JAN-08          1          2          4
21-NOV-06 17-FEB-08          1          2         27
21-JUN-06 17-JUL-08          2          0         26
SQL>But, don't forget that different months have different numbers of days, and leap years can effect it too.

Similar Messages

  • 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.

  • How to get the difference of two dates?

    let's say i have a table named tblData and has 4 columns: data_RefNo, data_DateReported, data_TargetDate, data_Data
    tblData returns 2 rows.
    data_RefNo.............data_DateReported.............data_TargetDate........................data_Data
    10000................10-20-2004 10:55:44 AM........10-20-2004 10:57:44 AM........Slow Response Time
    10000................10-21-2004 10:55:44 AM........10-21-2004 11:55:44 AM........Bug Error
    i just wana ask how to get the difference of the date_DateReported and date_TargetDate.
    i tried this code but it didnot work
    public Vector get_con_pf()
      Vector vData = new Vector();
      String query  = "SELECT * FROM tblData WHERE data_RefNo= '"'10000'"'";
      try
        DBConnect db = new DBConnect();
        db.openCon();
        ResultSet rs = db.execute(query);
        while (rs.next())
          vData.addElement(DATEDIFF(mi, rs.getString("st_DateReported"), rs.getString("st_TargetFinishDate")));
        db.closeCon();     
      catch (Exception e)
        System.out.println("Error: " + e );
      return vData;   
    i want to return the difference of the data_DateReported and date_TargetDate, i did this
    vData.addElement(DATEDIFF(mi, rs.getString("st_DateReported"), rs.getString("st_TargetFinishDate")));but it didnot work.
    How do i get that? because i want to return a vector.
    the code must return the values:
    2 for the 1st rows because the difference is only 2 minutes, and
    60 for the 2nd row.

    ooops i tried this one:
    query = "SELECT *, DATEDIFF(mi, data_DateReported, data_TargetDate) AS diff FROM tblData WHERE data_RefNo = '10000'";and it works.
    hehehehe!!!!!!
    problem solved! :)

  • How to get the difference between two dates???

    HI I have two dates and I want to test if there is an hour between them.
    Is there a way to compare two dates like mySQL can with dateDiff(date1,date2);
    Thanks alot.
    Graham

    This link is now out of date as they have revamped the structure. Yep. Here it is again: http://forum.java.sun.com/thread.jsp?forum=31&thread=502686
    I've also noticed that my comment regarding daylight saving was misleading. The demonstrated method for calculating difference between Dates is reliable. However, one needs to be careful when interpreting Dates in a daylight saving timezone.

  • Java code to get the difference between two dates in days

    Hi ppl,
    I need to write a user defined function to get the difference between two date nodes, in days.Please help me out
    regards,
    Prashanth

    Hi,
    have a look at those two:
    (How do I calculate the difference between two dates?)
    http://joda-time.sourceforge.net/faq.html
    Calculating the Difference Between Two Datetime Stamps
    http://www.xmission.com/~goodhill/dates/deltaDates.html
    Get difference in days
    http://javaalmanac.com/egs/java.util/CompDates.html
    Regards,
    michal

  • How to get the difference between two HashMaps

    i have two HashMaps
    HashMap first = new HashMap<Integer,Object>();
    HashMap second = new HashMap<Integer,Object>();
    How to get the difference between one and two and put the result in the third
    HashMap third = new HashMap<Integer,Object>();

    My bad, difference of course means removeAll():Map<Integer,Object> first = new HashMap<Integer,Object>();
    Map<Integer,Object> second = new HashMap<Integer,Object>();
    Map<Integer,Object> third = new HashMap<Integer, Object>(first);
    third.keySet().removeAll(second.keySet());No loops needed.

  • How to get the difference between two columns in a column group

    Hi All,
    My first time here and really new to programming. I would like to get the difference between 2 columns that are inside 
    a column group.
    Here is my sample table below: The Column Group is PeriodNumber and can only choose 2. like 1 and 2.. I would like to have a third row which will simply calculate the difference between the amounts in PeriodNumber 1 and 2.
                                PeriodNumber          
    Account                    1                            2     
    1) Cash                10,000                15,000
    2) Receivables      12,000                11,500
    3) Equipment          5,000                  5,500
    Total Assets          27,000                32,000

    Hi yabgestopa,
    From your description, you want to get the difference between two columns in a column group. After testing it in my environment, we can use custom code to achieve your requirement. For more details, you can refer to the following steps:
    Copy the custom code below and paste it to your report. (Right-click report>Report Properties>Code)
    Dim Shared Num1 As Integer
    Dim shared Num2 As Integer
    Public Function GetAmount(Amount as Integer, Type as String)
    If Type = "1" Then
    Num1=Amount
    Else
    Num2=Amount
    End If
    Return Amount
    End Function
    Public Function GetDif()
    Return Num1-Num2
    End function
    Right-click the second column to insert a third column with Outside Group-Right.
    Then use the expressions below in the matrix.
    =Code.GetAmount(Fields!Amount.Value,Fields!PeriodNumber.Value)
    =code.GetAmount(Sum(Fields!Amount.Value),Fields!PeriodNumber.Value)
    =Code.GetDif()
    The report looks like below.
    If you have any questions, please feel free to ask.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Date separate year, month and day

    Hello everyone and thanks in advance, I'm new to this and the truth is not doing this.
    Well, I have a PDF with several pages which I designed and has been asking me in a complete date in the format dd / mm / yy and subsequent pages he asks me the same date of birth but in 3 separate fields, day , month and year. I want you when you enter the date the first copy and separate day month and year in others. I tried this but I get
    var array_datesol = datesol.split("/")
    var year = parseInt(array_datesol[2]);
    var month = parseInt(array_datesoll[1]);
    var day = parseInt(array_datesol[0]);
    this.getField('yearsol').value = year;
    this.getField('monthsol').value = month;
    this.getField('daysol').value = day;
    where is the initial field datesol date and year, month and day where they have to be separately
    thanks in advance

    Are you getting any errors in the JavaScript debugging console?
    You are using the syntax for the 'Custom JavaScript calculation' and this syntax can not be used in the 'simplified field notation. Also you can not use any JavaScript properties, objects, functions, control statments.
    When run in the console, I find you have a misspelling of the variable name 'datesol'. I also do not see where you are initializing the value for 'datesol'.
    var datesol = event.valueAsString;  // get value of this field
    var array_datesol = datesol.split("/") ; // make into an array
    this.getField('yearsol').value =array_datesol[2];  // get element year
    this.getField('monthsol').value = array_datesol[1];  // get month element - fixed variable name
    this.getField('daysol').value = array_datesol[0]; // get date element
    I would use one of the following so the other fields are only updated when a date has been entered and the leading zeros are displayed:
    this.getField('yearsol').value = '';
    this.getField('monthsol').value = '';
    this.getField('daysol').value = '';
    if(event.value != '') {
    // get parts of date and print with leading zeros
    var datesol = event.value;  // get value of this field
    var array_datesol = datesol.split('/') ; // make into an array
    this.getField('yearsol').value = util.printf('%,304.0f', array_datesol[2]);  // get element year
    this.getField('monthsol').value = util.printf('%,302.0f', array_datesol[1]);  // get month element - fixed variable name
    this.getField('daysol').value = util.printf('%,302.0f', array_datesol[0]); // get date element
    // or
    this.getField('yearsol').value = '';
    this.getField('monthsol').value = '';
    this.getField('daysol').value = '';
    if (event.value != '') {
    // get date parts and print with leading zeros
    var oDatesol = util.scand('dd/mm/yyyy', event.value); // get date object
    this.getField('yearsol').value = util.printf('%,302.0f',oDatesol.getFullYear());  // get element year
    this.getField('monthsol').value = util.printf('%,302.0f', oDatesol.getMonth() + 1);  // get month element - fixed variable name
    this.getField('daysol').value = util.printf('%,302.0f', oDatesol.getDate()); // get date element
    // or
    this.getField('yearsol').value = '';
    this.getField('monthsol').value = '';
    this.getField('daysol').value = '';
    if(event.vaue != '') {
    // get parts of date and format
    var oDatesol = util.scand('dd/mm/yyyy', event.value); // get date object
    this.getField('yearsol').value = util.printd('yyyy', oDatesol); // get element year
    this.getField('monthsol').value = util.printd('mm', oDatesol); // get month element - fixed variable name
    this.getField('daysol').value = util.printd('dd', oDatesol); // get date element
    If you are going to fill other field, you will need to use the '.valueAsStriing' property or '.toString()'  method to retain the leading zeros.

  • How to get the diff between two dates  -  # of days

    Hi Experts,
    I have requirement to know the difference between dates. In my presentation layer two columns as created date and updated date. I want to know the difference in # of days in the presentation services.
    Please provide some pointers.
    Thanks in adv
    svr

    Hi,
    In the presentation layer you can create a column with a custom formula of this:
    TIMESTAMPDIFF(SQL_TSI_DAY, datecolumn1,datecolumn2)
    The result shown in the column will be the difference in days between the two dates.
    Regards,
    Matt

  • How to calculate the difference between two dates?

    Hello,
    I would like to write some code which figures out how many days are between the Date_of_change (which is of datatype DATE, length 7 and of format DD-MON-YY) and the current date today. Then if the difference between Date_of_change and the current date is greater that 30 days for example then I would like to delete that record from the database.
    Thanks
    Doug

    Something like this should work:
    SQL> select * from emp order by hiredate ;
         EMPNO ENAME      JOB              MGR HIREDATE           SAL       COMM     DEPTNO
          7934 MILLER     CLERK           7782 21-OCT-2005       1300                    10
          7902 FORD       ANALYST         7566 22-OCT-2005       3000                    20
          7900 JAMES      CLERK           7698 23-OCT-2005        950                    30
          7876 ADAMS      CLERK           7788 24-OCT-2005       1100                    20
          7844 TURNER     SALESMAN        7698 25-OCT-2005       1500          0         30
          7839 KING       PRESIDENT            26-OCT-2005       5000                    10
          7788 SCOTT      ANALYST         7566 27-OCT-2005       3000                    20
          7782 CLARK      MANAGER         7839 28-OCT-2005       2450                    10
          7698 BLAKE      MANAGER         7839 29-OCT-2005       2850                    30
          7654 MARTIN     SALESMAN        7698 30-OCT-2005       1250       1400         30
          7566 JONES      MANAGER         7839 31-OCT-2005       2975                    20
          7521 WARD       SALESMAN        7698 01-NOV-2005       1250        500         30
          7499 ALLEN      SALESMAN        7698 02-NOV-2005       1600        300         30
          7369 SMITH      CLERK           7902 03-NOV-2005        800                    20
    14 rows selected.
    SQL> delete from emp where hiredate < sysdate - 30 ;
    10 rows deleted.
    SQL> select * from emp order by hiredate ;
         EMPNO ENAME      JOB              MGR HIREDATE           SAL       COMM     DEPTNO
          7566 JONES      MANAGER         7839 31-OCT-2005       2975                    20
          7521 WARD       SALESMAN        7698 01-NOV-2005       1250        500         30
          7499 ALLEN      SALESMAN        7698 02-NOV-2005       1600        300         30
          7369 SMITH      CLERK           7902 03-NOV-2005        800                    20
    4 rows selected.
    SQL>

  • How to get the difference between two BufferedImages?

    All the BufferedImage which is grabbed from AWT may be same each other,
    i only want to get the different part of two continuous BufferedImages and send ti over internet.
    I have compared two BufferedImages by RGB (int[]), but this process wastes 400~500ms,it's terrible,:)
    who has any good idea about this?
    thanks
    Best Wishes
    mauvespan

    thanks ! cary ,
    I have a list contained some BufferedImages gotten from AWT component,and then these images
    will be transfered to client and displayed in Internet explore ,actually there are only some difference
    between two continuous BufferedImages,i don't want to transfer the WHOLE image to client,SO i
    want to handler every image before sending to client , at last, the different part will only be sent to client.
    All these ideas will be contained this method:
    * Compare the specified two BufferedImages and return the different part between them.
    * @param ref the specified first image
    * @param gen the specified sencond image
    * @return the different part between the specified two images.
    public static void BufferedImage compareBufferedImage(BufferedImage ref,BufferedImage gen){
    to finish this method ,do you have any good ideas?or sample code?
    thanks
    Best wishes
    mauvespan

  • How to find the difference between two date?

    Hi,
    I currently writing a date comparision program. Below is the idea analogy,
    Currently i need to find how many day differences between 30 July 2003 and 22 June 2004. How can i use java to code it?
    Thanks.

    there doesn't seem to be a direct way but try this:int daysBetween = 0;
    Calendar c = new GregorianCalendar(2004, Calendar.JULY, 30);
    Calendar d = new GregorianCalendar(2003, Calendar.JUNE, 22);
    while (c.get(Calendar.YEAR) != d.get(Calendar.YEAR)) {
        daysBetween += 360;
        d.add(Calendar.DAY_OF_YEAR, 360);
    daysBetween += c.get(Calendar.DAY_OF_YEAR) - d.get(Calendar.DAY_OF_YEAR);This gives the correct result of 404 (= 8 days from June 22 to June 30 + 366 days between July 1 of 2003 and 2004 + 30 days from July 1 to July 30)

  • 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

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Convert two dates difference to number of years, months and days

    Post Author: gigimonu
    CA Forum: Formula
    I wanted to write a formula (if there is a function I can use) that can convert a date difference to total number of years, months and days example
    adate = 10/22/2006
    ?xdate = current date - adate (answer should be 1 years, 0 months and 0 days)
    Please help
    Thanks

    Post Author: V361
    CA Forum: Formula
    &#91;Years, Months, Days&#93;
    DATEVAR FROMDATE := DATE(2000,01,01); // FROM DATE
    DATEVAR TODATE := CURRENTDATE; // TO DATE
    NUMBERVAR YEARS;
    NUMBERVAR MONTHS;
    NUMBERVAR DAYS;
    STRINGVAR DIFF;
    DATEVAR TEMP;
    IF TODATE < FROMDATE THEN
    (TEMP := TODATE;
    TODATE := FROMDATE;
    FROMDATE := TEMP);
    YEARS := DATEDIFF('YYYY',FROMDATE,TODATE);
    IF YEARS > 2 THEN
    (YEARS := YEARS - 2;
    TEMP := DATE(DATEADD("M",YEARS * 12,FROMDATE));)
    ELSE
    (YEARS := 0;
    TEMP := FROMDATE);
    WHILE TRUE DO
    (TEMP := DATE(DATEADD('M',1,TEMP));
    IF TEMP > TODATE THEN
    EXIT WHILE;
    MONTHS := MONTHS + 1);
    DAYS := DATEDIFF('D',DATE(DATEADD('M',-1,TEMP)),TODATE);
    IF MONTHS > 12 THEN
    (YEARS := YEARS + INT(MONTHS/12);
    MONTHS := MONTHS MOD 12);
    DIFF := IIF(YEARS>0 ,TRIM(TOTEXT(YEARS,0)) & " YEARS " ,"0 YEARS ") &
    IIF(MONTHS>0,TRIM(TOTEXT(MONTHS,0))& " MONTHS ","0 MONTHS ")&
    IIF(DAYS>0 ,TRIM(TOTEXT(DAYS,0)) & " DAYS" ,"0 DAYS");

Maybe you are looking for