How to get the difference in Date in years, months and days

Select Sysdate-Birth_date from Employees;
the query returns the number of days between two dates
I want to convert this number in years, months and days
Can someone help me please

Hoek wrote:
Try:

SQL> with t as (
2  select to_date('01-01-1980', 'dd-mm-yyyy') birthdate
3  ,      to_date('05-05-2010', 'dd-mm-yyyy') today
4  from   dual
5  )
6  --
7  --
8  --
9  select extract(year from today)-extract(year from birthdate) years
10  ,      extract(month from today)-extract(month from birthdate) months
11  ,      extract(day from today)-extract(day from birthdate) days
12  from   t;

YEARS     MONTHS       DAYS
---------- ---------- ----------
30          4          4

1 row selected.

(May need some adjustments, possibly using the LARGEST, but currently not as long)

Indeed, a few adjustments...

SQL> ed
Wrote file afiedt.buf

  1  with t as (
  2    select to_date('31-01-2009', 'dd-mm-yyyy') birthdate
  3    ,      to_date('28-02-2010', 'dd-mm-yyyy') today
  4    from   dual
  5    )
  6  --
  7  --
  8  --
  9  select extract(year from today)-extract(year from birthdate) years
 10  ,      extract(month from today)-extract(month from birthdate) months
 11  ,      extract(day from today)-extract(day from birthdate) days
 12* from   t
SQL> /

     YEARS     MONTHS       DAYS
---------- ---------- ----------
         1          1         -3

SQL>

Maybe 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('31-jan-2009','dd-mon-yyyy'), to_date('28-feb-2010','dd-mon-yyyy') from dual union all
  4             select to_date('21-jun-2006','dd-mon-yyyy'), to_date('17-jul-2008','dd-mon-yyyy') from dual
  5             )
  6  -- end of test data
  7  select c_start_date, c_end_date
  8        ,trunc(months_between(c_end_date, c_start_date) / 12) as yrs
  9        ,trunc(mod(months_between(c_end_date, c_start_date), 12)) as mnths
 10        ,trunc(c_end_date - add_months(c_start_date, trunc(months_between(c_end_date, c_start_date)))) as dys
 11* from t
SQL> /

C_START_DATE        C_END_DATE                 YRS      MNTHS        DYS
------------------- ------------------- ---------- ---------- ----------
17/11/2006 00:00:00 21/01/2008 00:00:00          1          2          4
21/11/2006 00:00:00 17/02/2008 00:00:00          1          2         27
31/01/2009 00:00:00 28/02/2010 00:00:00          1          1          0
21/06/2006 00:00:00 17/07/2008 00:00:00          2          0         26

Tags: Database

Similar Questions

  • How to find the difference in date in years, months and days

    Hello
    I need to find the difference between 2 dates in the following way "years months days". "
    Please can help me, how can I achieve this.

    for example, in the scott schema emp table, I need to find the difference in date between sysdate and hiredate for an employee in the following way.

    12 years 7 months 4 days.

    Hello

    Please, see this post to AskTom [difference between 2 dates | http://asktom.oracle.com/pls/asktom/f?p=100:11:0:P11_QUESTION_ID:96012348060]. There is good information in this forum, for example you can also see this thread [calculation of years, months & days | http://forums.oracle.com/forums/thread.jspa?messageID=3115216�]

    Kind regards

    Published by: Walter Fernández on November 30, 2008 08:58 - adding another link

  • How to get the difference in dates in days

    Hi friends,

    How to get the date difference between two dates exactly

    date2-date1 days exactly... shouyld rounded to the nearest value of...

    and one entire display i mean positive integer
    Select round ((sysdate) - to_date (date_start)), date_start days of per_periods_of_service

    This gives negative also result

    Hello

    776317 wrote:
    Hi friends,

    How to get the date difference between two dates exactly

    date2-date1 days exactly... shouyld rounded to the nearest value of...

    Date1 - date2 is the exact number of days is after date2 date1. (It is as accurate as possible, given that the DATEs do not have fractions of a second).

    and one entire display i mean positive integer
    Select round ((sysdate) - to_date (date_start)), date_start days of per_periods_of_service

    You want to probably get the exact number of days first, then ROUND this number:

    SELECT  ROUND (SYSDATE - TO_DATE (date_start, ...))   AS days
    FROM    per_periods_of_service; 
    

    Always pass arguments at least 2 to TO_DATE:
    (1) the string to be converted, and
    (2) a saying string how (1) is formatted

    This gives negative also result

    Right; If date1 is before date2 then date1 - date2 returns a negative number.
    If you want to never get a negative value, use ABS (date2 - date1). If it returns 4, then you know that one of the DATEs was 4 days before the other, but you won't know who was earlier.

    I hope that answers your question.
    If not, post a small example data (CREATE TABLE and only relevant columns, INSERT statements) and also publish outcomes from these data.
    Explain, using specific examples, how you get these results from these data.
    Always tell what version of Oracle you are using.

  • How to get the difference of two dates in months

    Dear friends,

    I have 4 items on my page.

    2 entered message text (value of loan, monthly deduction)

    2 are message style fields (start date, end date)

    I need to get the difference from above 2 dates in no.. of months. (for example say N)

    So with N, loanvalue should be divided and populated as monthly deduction.

    I tried this way, but not able to get the difference of dates

    {if ("populateMonthlyDeduction". Equals (PageContext.GetParameter (EVENT_PARAM)))}

    System.out.println ("enter populateMonthlyDeduction loop1");

    String xxDeductionStartDate = vo.getCurrentRow ().getAttribute("DeducStartDt").toString ();

    System.out.println ("xxDeductionStartDate is:" + xxDeductionStartDate);

    TXN OADBTransaction = am.getOADBTransaction ();

    java.sql.Date DeductionSDate = null;

    java.sql.Date DeductionEDate = null;

    if(xxDeductionStartDate!=null)

    {

    java.sql.Date startDate = txn.getOANLSServices () .stringToDate (xxDeductionStartDate);

    DeductionSDate = startDate;

    System.out.println ("DeductionSDate is:" + DeductionSDate);

    }

    String xxDeductionEndDate = vo.getCurrentRow ().getAttribute("DedEndDt").toString ();

    if(xxDeductionEndDate!=null)

    {

    java.sql.Date endDate = txn.getOANLSServices () .stringToDate (xxDeductionEndDate);

    DeductionEDate = endDate;

    System.out.println ("DeductionEDate is:" + DeductionEDate);

    }

    int difInDays = xxDeductionEndDate-xxDeductionStartDate; -Please correct me

    How reach it .plz help.

    Thank you

    Aravinda

    I used a custom like this method and calls this method daysBetween PFR.

    I got it. Thanks to you all.

    public int daysBetween(As Date, Date etDate)

    {

    return (int) ((etDate.getTime () - stDate.getTime (()) / (1000 * 60 * 60 * 24));

    }

    If ("populateMonthlyDeduction". Equals (PageContext.GetParameter (EVENT_PARAM)))

    {

    System.out.println ("enter populateMonthlyDeduction loop1");

    String dedStDt = vo.getCurrentRow ().getAttribute("DeducStartDt").toString ();

    String dedEndDt = vo.getCurrentRow ().getAttribute("DedEndDt").toString ();

    If (! dedStDt.Equals (null) &! dedEndDt.equals (null))

    {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    Date sdate = new Date();

    Date edate = new Date();

    String sdate1 = null;

    String edate1 = null;

    try {}

    sdate = dateFormat.parse (dedStDt);

    EDATE = dateFormat.parse (dedEndDt);

    SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd-MMM-yyyy");

    sdate1 = dateFormat1.format (sdate);

    edate1 = dateFormat1.format (edate);

    int days = daysBetween(sdate, edate);

    int diffInMonths = days/30;

    System.out.println ("days is:" + days);

    System.out.println ("diffInMonths is:" + diffInMonths);

    String sTotValueTuitionFees = vom.getCurrentRow ().getAttribute("TotValueTuitionFees").toString ();//pageContext.getParameter("LoanValue").toString();

    int iTotValueTuitionFees = Integer.parseInt (sTotValueTuitionFees);

    int iMonthlyDeduction = iTotValueTuitionFees/diffInMonths;

    String sMonthlyDeduction = String.valueOf (iMonthlyDeduction);

    System.out.println ("iMonthlyDeduction is:" + sMonthlyDeduction);

    OAMessageStyledTextBean bMonthlyDeduction = (OAMessageStyledTextBean) webBean.findChildRecursive ("MonthlyDeduction");

    bMonthlyDeduction.setValue (pageContext, sMonthlyDeduction);

    }

    catch (ParseException exception) e

    {

    }

    }

    }

  • How to get the timestamp of data DAQmx Read

    Hello

    I have to read 4 analog channels using DAQmx AI read in LabVIEW 2012. I am using screws DAQmx.

    Acquisition rate is 4000 samples per second, and the number of samples per channel is 200.

    I use only one task DAQmx to read the data. I get 4 data tables for 4 channels each table length is 200, every time, DAQmx Read happens.

    But I want to get the seal of these 200 samples per channel. How to get the seal of these samples, made me know.

    Thank you

    You have not indicated your code. If you choose to read the waveform data, the cluster includes t0 and dt. That's all the information you need.

  • How to convert days to years, months and days remaining

    Hi all
    I have the number of days for example: 398 days how
    convert 398 days to several years, and the number of months and days remaining
    398 days 1 year, 1 month and 2 days
    Concerning
    Jocelyne

    There is no correct answer.

    That's right! ;)

  • How to get the Application Build Date and time?

    Hi guys,.

    I am developing application in Cascade.

    What is the API I can use to get the construction Date of the application and Tiime?

    These macros are expanded to C-strings at compile time. This is how/where to use it. Following an example would work I think:

    fprintf (stderr, "construction date is %s, construction time is %s\n", __DATE__, __TIME__);

  • How to get the difference of current and previous line for a column of the same table?

    Hello

    I have a table where there are 3 rows and say 2 columns only, as below

    Col1               | Col2
    --------------------- |----------------------------------------

    first_flag |  100

    second_flag |  104

    third_flag |  110

    Now, using sql, which accepts a parameter col1, how do I get the bottom o/p

    say that the entry is second_flag,

    output must be

    second_flag, 104, 4 (4 being the difference between 104 and 100)

    If I give the entry like third_flag, the output should be

    third_flag, 110, 6 (6 is the difference between 110 and 104)

    Any help?

    Hello

    Another way is to use the analytic LAG function:

    WITH got_diff AS

    (

    SELECT col1, col2

    , col2 - LAG (col2) over (ORDER BY col1) AS diff

    OF mydata

    )

    SELECT *.

    OF got_diff

    WHERE col1 =: flag_wanted

    ;

    This assumes that the lines are in alphabetical order by col1.  If the order is something else, then use it in the ORDER BY clause analytical.

  • How to get the control instance data in Bean managed when data mutiple controls exist

    Below is my way. This works if there is only one control. is there an api that can be used to get the instance of the data control by name?

            DCDataControl dc = BindingContext.getCurrent().getDefaultDataControl();
            if(dc != null){
                AppModuleImpl am = (AppModuleImpl)dc.getApplicationModule();
               ...
             }
    

    I don't want to use this medium orginial.

          String amDef = "model.AppModule";
          String config = "AppModuleLocal";
          ApplicationModule am = Configuration.createRootApplicationModule(amDef, config);
          ViewObject vo = am.findViewObject("ObjectView1");
    

    Hello

    I guess you have a binding method as the first activity in your stubborn workflow. Open your workflow in preview mode, right-click on your connection method and say «Go to the PageDef» This will create a definition file page for the binding of your method. You can use this to put the iterator binding that you want to access from your init method.

    Rami

  • How to get the time to date?

    Hi Sir,

    I need to recover the time to date.

    ' like ' 2012-10-03 04:32.

    to retrieve the only time where it's 04:32

    What is the query for this?

    Thank you

    Hi user,

    You can use TO_CHAR function to obtain the hour alone

    SELECT TO_CHAR (TO_DATE ('2012-10-03 04:32:00', 'YYYY-MM-DD HH24:MI:SS'),
                    'HH24:MI:SS'
                   ) TI_ME
      FROM DUAL
    

    Thank you
    Shankar

  • How to get the content of a textarea with bbui and jquery

    Hi, I have a problem. I build an app with bbUI and jQuery. Now, I need to get the content of a Textare when someone clicks on the record in the next page:

    Text Entry Examples
    Text Area

    my javascript code looks like this:

    function save() {
        alert($("#myinput").text());
    }
    

    what I have to change to get this working? I don't get the "123", but when I change it is always '123 '.

    I believe you can use the .val property.

    $("#id").val()
    
  • How to get the jar file without knowing his name and any class on the inside?

    Hello, everyone!

    I would like to know if there is a way to get a reference programmatically in the original container without knowing his name and any class it contains. I mean by "initial pot" the pot that was called in the prompt, like this:
    java -jar jarfile.jar
    or in another way, in a graphics system. To be honest, what I really want is to get a reference to the manifest of the jar, but I know that if I can get a reference to the jar I can get a reference to its manifest file. Or if you know a way to get the manifest directly, it would also be useful. So, is there a way to do this?

    Thank you.

    Marcos

    Ah, so you want to find the calling class and get its source code.

    I managed to get the class calling on occasion, but this is probably a somewhat fragile solution. You must extend SecurityManager because getClassContext() is a protected method.

        private static class CallerFetch extends SecurityManager {
    
            public Class getCallerClass() {
                return getClassContext()[3];
            }
        }
        private static CallerFetch callerFetch =
                new CallerFetch();
    
        /**
         * Find the class of the code which called the
         * method that invokes this method.
         * @return The class of the caller's caller
         */
        public static Class getCallerClass() {
            return callerFetch.getCallerClass();
        }
    
  • How to get the key for windows 7 already installed and supplied with the laptop.

    I bought Lenovo laptop, 2 years back, and he had windows 7 Home premium.  Now it is showing my windows cannot be real and asks for the key for verification. Key was written on a label on the back of my laptop. The key is now unreadable on the sticker. I'm looking for the key to verification?

    If the product key on the COA sticker is damaged, then your options include:

    Reinstall Windows 7 using the supplied with your laptop Lenovo recovery partition:

    http://www-307.IBM.com/PC/support/site.WSS/document.do?lndocid=MIGR-4HWSE3

    Computers laptops Lenovo include a function called the Lenovo OneKey Recovery button, which is used to boot into the recovery environment and to reinstall Windows.

    If this does not work, contact technical support http://www-307.ibm.com/pc/support/site.wss/homeLenovo.do and request replacement CD-ROM

    If these options are not available, you will need to purchase a new product key for Windows 7 Home Premium.

    You can also try to do a restore of the system before you start, facing this problem to see if suits him.

  • Calendar.setTime defines the only year, month and day, no time

    Hello

    It is more a question of JAva instead of JDeveloper, but I still hope to get some answers here. I have problems, I have a Date (oracle.jbo.domain.Date) 2008-12-12 15:21:0. What I need is a string '121521' (day, hour, and minute - DDHHMM). This should be simple, but I'm strugling with this for a while now: $. I use class schedule so I can get the values using cal.get (Calendar.DAY_OF_MONTH), cal.get (Calendar.HOUR_OF_DAY) and cal.get (Calendar.MINUTE).

    Think I tried and none of them work:
          Calendar cal = Calendar.getInstance();
              Date ldETA = (Date)loETA; // this is the oracle.jbo.domain.Date 12/12/2008 15:21:0
    
              cal.clear();
              cal.setTime(ldETA.dateValue());
             // I try getting the values here
              try {
                cal.clear();
              cal.setTimeInMillis(ldETA.longValue());
             // I try getting the values here
              }
              catch (Exception e) {}
              
              java.util.Date loD = (java.util.Date)ldETA.dateValue();
              cal.clear();
              cal.setTime(loD);
             // I try getting the values here
    I always get only 12 for cal.get (Calendar.DAY_OF_MONTH) while cal.get (Calendar.MINUTE) and cal.get (Calendar.HOUR_OF_DAY) return 0.

    Help please: (.)

    Thank you
    BB

    BB,

    oracle.jbo.domain.Date is a subclass of oracle.sql.DATE, which has a method toText() - have you tried?

    John

  • How to make the difference between data (different sensors and actuators) is tans/recvd using series com

    Hello

    I get 2 different types of data from the controller. How to differentiate b/w them.

    After receiving my code in deccissions. There are 6 different control elements in my project attached to the controller. Thanks for give me idea how I send data to the controller for this controller to differentiate that exit to be active or low

    First, look at the couple of serial examples that come with LabVIEW. You use the VISA functions to read and write. Your technique to separate the values will work as well in LabVIEW. You would be to convert the string returned by VISA reading to a digital (i.e. with the Scan of the chain). Then do the comparison, then the result of wire to one of the two indicators. Put the terminal of each indicator inside a case statement would be a way to do it.

Maybe you are looking for