Difference Bet~n two dates?

Hi
can u write a function which can return a string having the difference between two input dates? That must be in X Year,X days, X hours,X minutes,X seconds.
Just think One person was born in 01/01/1979 05:20:30.
Today just now the date is 25/09/2004 16:51:30.
What is the age of that person right now?
Please help me in detail in SQL code.
FARHAD

There are several ways you could do this.
The following example should help you.
SQL> declare
  2  date1 date;
  3  date2 date;
  4  v_years pls_integer;
  5  v_days pls_integer;
  6  v_partial_days number;
  7  v_hours pls_integer;
  8  --v_hours2 number;
  9  v_minutes pls_integer;
10  v_dseconds pls_integer;
11  v_dseconds2 pls_integer;
12  v_seconds pls_integer;
13  begin
14     date1 := to_date('25/09/2004 16:21:29','DD/MM/YYYY HH24:MI:SS');
15     date2 := to_date('01/01/1979 05:20:30','DD/MM/YYYY HH24:MI:SS');
16     select trunc(months_between(date1,date2)/12) years
17       into v_years
18       from dual;
19 
20     select trunc(date1 - add_months(date2, 12*v_years))
21       into v_days
22       from dual;
23 
24     select trunc(((date1 - add_months(date2,12*v_years)) - v_days)*24)
25       into v_hours
26       from dual;
27 
28     select to_number(to_char(date1,'MI'))*60 + to_number(to_char(date1,'SS')),
29            to_number(to_char(date2,'MI'))*60 + to_number(to_char(date2,'SS'))
30       into v_dseconds,v_dseconds2
31       from dual;
32     if v_dseconds < v_dseconds2 then
33        v_dseconds := v_dseconds + 3600;
34     end if;
35     v_minutes := trunc((v_dseconds-v_dseconds2)/60);
36     v_seconds := v_dseconds - v_dseconds2 - v_minutes*60;
37 
38     dbms_output.put_line(v_years);
39     dbms_output.put_line(v_days);
40     dbms_output.put_line(v_hours);
41     dbms_output.put_line(v_minutes);
42     dbms_output.put_line(v_seconds);
43  end;
44  /
25
268
11
0
59
PL/SQL procedure successfully completed.

Similar Messages

  • Facing problem while calculating the difference between the two dates?

    Hi
    I am using this code to calculate the difference between the two dates :
    import java.util.Calendar;
    import java.util.*;
    public class DateDifferentExample
    public static void main(String[] args)
    // Creates two calendars instances
    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    // Set the date for both of the calendar instance
    cal1.set(2006, 12, 30);
    cal2.set(2007, 05, 03);
    // Get the represented date in milliseconds
    long milis1 = cal1.getTimeInMillis(); // getting error here
    long milis2 = cal2.getTimeInMillis(); // getting error here
    // Calculate difference in milliseconds
    long diff = milis2 - milis1;
    // Calculate difference in seconds
    long diffSeconds = diff / 1000;
    // Calculate difference in minutes
    long diffMinutes = diff / (60 * 1000);
    // Calculate difference in hours
    long diffHours = diff / (60 * 60 * 1000);
    // Calculate difference in days
    long diffDays = diff / (24 * 60 * 60 * 1000);
    System.out.println("In milliseconds: " + diff + " milliseconds.");
    System.out.println("In seconds: " + diffSeconds + " seconds.");
    System.out.println("In minutes: " + diffMinutes + " minutes.");
    System.out.println("In hours: " + diffHours + " hours.");
    System.out.println("In days: " + diffDays + " days.");
    but i am getting this error :
    The method getTimeInMillis() from the type calendar is not visible
    Please suggest!!

    // Get the represented date in milliseconds
    long milis1 = cal1.getTime().getTime(); // getting error here
    long milis2 = cal2.getTime().getTime(); // getting error here Hope this works for you!!

  • How to get the difference between these two dates

    Hello Friends,
    I need to get the difference between these two fields which store dates but with varchar2 data types
    SELECT pac.segment1, pac.segment2 emp_no, pac.segment3 NAME,
    pac.segment4 POSITION, pac.segment5 start_date, pac.segment6,
    pac.segment7
    FROM per_analysis_criteria pac, fnd_id_flex_structures_vl ffs
    WHERE ffs.id_flex_structure_code = 'Employee Rejoin'
    AND ffs.id_flex_num = pac.id_flex_num
    AND TO_CHAR (TO_DATE (pac.segment7, 'YYYY/MM/DD HH24:MI:SS'))
    - TO_CHAR (TO_DATE (pac.segment6, 'YYYY/MM/DD HH24:MI:SS')) > 1;
    my query is something like this...
    am trying to find the difference between the last two columns but with not much luck..
    can some one suggest me a solution please

    SELECT pac.segment1, pac.segment2 person_id, pac.segment3 NAME,
    papf.employee_number, paaf.supervisor_id, pac.segment4 POSITION,
    pac.segment5 start_date, pac.segment6, pac.segment7,
    papf2.email_address,
    ( TO_DATE (TO_CHAR (pac.segment7), 'DD-MON-YYYY HH:MI:SS AM')
    - TO_DATE (pac.segment6, 'DD-MON-YYYY HH:MI:SS AM')
    + 1
    ) difference,
    POST.email_address
    FROM per_analysis_criteria pac,
    apps.fnd_id_flex_structures_vl ffs,
    per_all_people_f papf,
    per_all_assignments_f paaf,
    per_all_people_f papf2,
    (SELECT email_address, person_id
    FROM per_all_people_f
    WHERE person_id IN (
    SELECT person_id
    FROM per_all_assignments_f
    WHERE position_id IN (SELECT position_id
    FROM per_positions
    WHERE NAME LIKE 'HR Manager.704.')
    AND TRUNC (SYSDATE) BETWEEN effective_start_date
    AND effective_end_date)
    AND TRUNC (SYSDATE) BETWEEN effective_start_date AND effective_end_date
    AND business_group_id = fnd_profile.VALUE ('PER_BUSINESS_GROUP_ID')) POST
    WHERE ffs.id_flex_structure_code = 'Employee Rejoin'
    AND TO_CHAR (papf.person_id) = pac.segment2
    AND ffs.id_flex_num = pac.id_flex_num
    AND TRUNC (SYSDATE) BETWEEN papf.effective_start_date
    AND papf.effective_end_date
    AND papf.current_employee_flag = 'Y'
    AND papf.person_id = paaf.person_id
    AND TRUNC (SYSDATE) BETWEEN paaf.effective_start_date
    AND paaf.effective_end_date
    AND papf.person_id = paaf.person_id
    AND papf2.person_id = paaf.supervisor_id
    AND paaf.primary_flag = 'Y'
    AND TRUNC (SYSDATE) BETWEEN papf2.effective_start_date
    AND papf2.effective_end_date
    AND papf2.current_employee_flag = 'Y'
    and ( TO_DATE(to_char(pac.segment7), 'DD-MON-YYYY HH:MI:SS AM')-TO_DATE (pac.segment6, 'DD-MON-YYYY HH:MI:SS AM')+1) >1
    last line is giving me the error pls suggest a solution

  • Using trunc as difference measure btwn two dates

    I have a SQL query that works smoothly. It takes the difference between sets of dates that are >=0 and <=0. here it is:
    SELECT createdate,  id, objid, start_date, end_date
    FROM greggs_date, HNEMap
    where active =1
    and trunc (createdate-start_date) >=0  and trunc (createdate-end_date) <=0;
    Problem is I can't output the differences. In MS SQL Server you can show the number of days difference with the datediff function named in the SELECT part of the SQL statement not so with trunc used to get date differences. How can this query be rework to show the actual days of difference between start and end from create date.

    Hi,
    robleh7 wrote:
    I have a SQL query that works smoothly. It takes the difference between sets of dates that are >=0 and <=0. here it is:
    SELECT createdate,  id, objid, start_date, end_date
    FROM greggs_date, HNEMap
    where active =1
    and trunc (createdate-start_date) >=0  and trunc (createdate-end_date) <=0;
    Problem is I can't output the differences. In MS SQL Server you can show the number of days difference with the datediff function named in the SELECT part of the SQL statement not so with trunc used to get date differences. How can this query be rework to show the actual days of difference between start and end from create date.
    Sorry, I don't understand the problem.
    TRUNC (createdate - startdate)    is just a NUMBER.  You can display it just like any other NUMBER.
    SELECT  k.hiredate                         AS base_date
    ,       d30.hiredate
    ,       TRUNC (k.hiredate - d30.hiredate)  AS dif
    FROM        scott.emp  k
    CROSS JOIN  scott.emp  d30
    WHERE   k.ename        = 'KING'
    AND     d30.deptno     = 30
    Output:
    BASE_DATE   HIREDATE           DIF
    17-Nov-1981 20-Feb-1981        270
    17-Nov-1981 22-Feb-1981        268
    17-Nov-1981 28-Sep-1981         50
    17-Nov-1981 01-May-1981        200
    17-Nov-1981 08-Sep-1981         70
    17-Nov-1981 03-Dec-1981        -16
    Post a complete test script (including CREATE TABLE and INSERT statements, if needed)  and the results you want from that script.

  • What is GL account, difference bet. Doc.date and posting date, etc.

    Hello Experts,
    Currently I am supporting reports/programs for FI module. Can anybody please help
    me or give me walkthrough on what are the terms like posting key, document date,
    posting date, type, account, etc. I am currently modifying a report which posts in
    transaction F-02. Any tips and guides will be highly appreciated. Thanks guys and take care!

    Hi,
    <b>GL Account:</b> This field contains the number of the G/L account to which the transaction figures are updated.we use One gl account for Salaries in an Orgn, and for expenses one GL like that.
    <b>Document Date</b>: The document date is the date on which the original document was issued.
    <b>Posting date:</b>Date which is used when entering the document in Financial Accounting or Controlling
    The fiscal year and the period for which an update of the accounts specified in the document or cost elements is made, are derived from the posting date.
    When entering documents, the system checks whether the posting date entered is allowed by means of the posting period permitted.
    The posting date can differ from both the entry date (day of entry into the system) and the document date (day of creation of the original document).
    <b>Posting Key:</b>The posting key describes the type of transaction which is entered in a line item.
    For every posting key, you specify properties which control the entry of the line item or are noted in the line item itself.
    The most important properties which are derived from the posting key are:
    The account type
    The allocation to the debits or credits side
    The possible or necessary specifications which are to be entered in the line item.
    <b>DocType:</b>The document type classifies the accounting documents. It is stored in the document header.
    Attributes that control the entry of the document, or which are themselves noted in the document, are defined for each document type. In particular, the number range assigned to the associated documents is defined on the basis of the document type.
    reward if useful
    regards,
    Anji

  • 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

  • Calculating difference between two dates in Variable Exits

    Hi,
          I need to calculate the difference between the two dates in months in Variable exits. I want the result in months so that I need to find out the Average Usage.
            How can I find the difference between them in months.
    Thanks
    Dave.

    Hi Christophe, Senthil
                                       Sorry for late response, I checked this  MONTHS_BETWEEN_TWO_DATES_NEW  in SE37/SE38 and about the date they are going to enter at query run time it should be like 03/03/2006 to 08/03/2006 and I should get in 5 months and or if the date range 03/15/2006 to 08/03/2006 and I should get like 4.5 months. Please could you tell me how to get the values in months or please give me a functional module so that I can use.
    Thanks
    Dave.

  • 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

  • Difference between two dates in seconds/milliseconds with Expressions

    Hi,
    I need to write a query using Expression(Builder) which calculates the difference between two columns (date/timestamps). As of other requirements I am not able to use JPQL, so I tried to create the query with the Expression framework. The difference between the two dates can be calculated with the
    ExpressionMath.substract(...)
    method. The result is a Date-like object storing the difference between both dates. But how can I cast this difference to a long or something like this with expressions?
    Thanks,
    Thomas

    Date functions are very database dependent, as each database has its own set of functions for processing dates.
    The functions are defined in the Expression class, you can try,
    truncateDate, roundDate, or datePart
    http://www.eclipse.org/eclipselink/api/1.1.2/org/eclipse/persistence/expressions/Expression.html#truncateDate(java.lang.String)
    http://www.eclipse.org/eclipselink/api/1.1.2/org/eclipse/persistence/expressions/Expression.html#roundDate(java.lang.Object)
    http://www.eclipse.org/eclipselink/api/1.1.2/org/eclipse/persistence/expressions/Expression.html#datePart(java.lang.String)
    James : http://www.eclipselink.org

  • [Urgent] Need help calculating difference between two dates

    I'm trying to write a code to display the current day and time, then accept two dates from the user and display the difference between the two dates. To display the current date and time, I've used the SimpleDateFormatter library but I'm having difficulty calculating the difference between two dates. Could someone please help me with this?
    Below is my code so far
    import java.util.Date;
    import java.util.Scanner;
    import java.text.SimpleDateFormat;
    public class DateFormatter {
         public void displayNow()
              Date todaysDate = new Date();
              SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
              String formattedDate = formatter.format(todaysDate);
              System.out.println("Today's date and time is: "+formattedDate);
         public void calculateDifference(Date startDate, Date endDate)
              /* This is whre i need help! */
         public static void main(String[] args)
              DateFormatter df = new DateFormatter();
              Scanner sc = new Scanner(System.in);
              df.displayNow();
              System.out.println("Please enter a date: ");
              String date1 = sc.next();
              System.out.println("Please enter another date: ");
              String date2 = sc.next();
    }The methods displayNow() and calculateDifference(Date startDate, Date endDate) are essential and cannot be skipped out.

    tarahmarie101 wrote:
    Dude. I've tried doing assignments under pressure, and it doesn't work. Here's a piece of free advice. Start earlier next time, don't put "urgent" in the title of your post b/c it just pisses people off around here--and is a sure sign of an overdue homework assignment which no one around here likes helping with, and try to ask intelligent questions--don't just say "Help me!"
    Of course, it takes some time to learn what the intelligent questions are. You have my sympathy. Try asking questions about how to do a particular task, instead of asking people to tell you what to do. It starts to get easier after a while.
    actually dude i started on this on monday.. but there were so many other stuff to do along with this.. and i did try referring up the Calendar utility but it was a bit confusing actually.. it was only after that did i come to this forum.. nor am i very good at Java.. anyhoo thanks for your sympathies :P

  • (Groovy Expression) Get the no. of days between two dates

    Hi All,
    I am using ADF-BC-11g to create an entity object with 2 specific columns ActualDate and EstimatedDate both of Date type. I also want an additional field DaysBetweenTwoDates showing the difference between these two dates. Hence, I add another attribute DaysBetweenTwoDates in my entity object and after removing the Persistent property, I modify the expression field as ActualDate - EstimatedDate. When I test my AM, I get an error as below:
    *(oracle.jbo.JboException) JBO-29000: Unexpected exception caught: groovy.lang.MissingMethodException, msg=No signature of method: java.sql.Date.minus() is applicable for argument types: (java.sql.Date) values: {2009-04-01}*
    Can anyone please tell me how to achieve the same?
    Please note that I can not add a new column DaysBetweenTwoDates in the table nor can I have a new VO attribute subtracting and storing the difference as there are some logical and refreshing constraints.
    Any suggestions would be really helpful.
    Thanks
    Neeraj

    Thanks John,
    Oops...I did not think on this ground at all. Thanks for directing towards right direction. However, just to know, is that possible anyways thorugh groovy expression? Do we have any docs where we can search for the functions available in groovy expression?
    Regards,
    Neeraj

  • Calculate difference in value based on two date parameters

    Hi All,
    I have a table and need to calculate the difference in rent amount for a property based on two date parameters.
    I have uploaded sample data here:
    https://app.box.com/s/pu8oa4f3jhrhm0ylshdz2fuo7541vn4z
    Thanks
    Jag

    Hi jaggy99,
    Do you have the knowledge of
    Excel Add-In? If you don't have knowledge of C#/VB.NET language and Visual Studio, I don't think Excel Add-In is what you want. As I said previously, your problem is totally about the business logic, we don't provide solution for a complete requirement.
    Based on your sample data, I think VBA code is suitable.
    If you're not familiar with VBA, please take a look at the MSDN documents for scratch:
    Getting Started with VBA in Excel 2010
    The steps should be like this:
    1. Sort all the records by [Rent Change Date] field
    2. Loop throuth the records and find the FromDate and ToDate as well as the corresponding [Rent Charged] field
    3. Calculate the difference and save the data into a new range
    It's not so hard, please have a try, if you encounter any development problems, you can post in this forum.
    Thanks.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

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

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

  • How do you work out the number of days difference between two dates?

    I'm running Crystal v12.
    We use a date field in our SQL database that we use to store the client's year end date.
    As the year end date (date and month) doesn't change for a client, the year end date field in all of our reports is set to just show the DD/MM part. Over the years as new clients are set up we just enter the date and month - the year part is irrelevant although as in all date fields the year is automatically entered.
    Doing it this way means that we don't have to adjust the year end year part each year. We just use the DD/MM part.
    I need to create a formula that works out the number of days there have been (i.e. the difference) from the current date to the year end date. It MUST EXCLUDE the year however.
    For example:
    Year End Date = 30/04/03
    Current Date = 25/05/10
    Days Difference (EXCLUDING year) = 25
    Days Difference (including year) = 2582
    Year End Date = 31/03/09
    Current Date = 25/05/09
    Days Difference (EXCLUDING year) = 55
    Days Difference (including year) = 420
    If you include the year part then working out day difference is simply a case of creating a formula that subtracts the year end date from the current date (CurrentDate - {tblClient.YearEnd}.
    HOWEVER I need to exclude the year part.
    Can anyone tell me the formula or best way to do this?
    Thanks in advance.
    Edited by: BadBoy House on May 25, 2010 3:15 PM
    Edited by: BadBoy House on May 25, 2010 3:15 PM

    Hi
    You can try this
    datevar e := date(year(currentdate),month({tblClient.YearEnd}),day({tblClient.YearEnd}));
    numbervar num_days := datediff("d",currentdate,e)
    Create a datevar called e that uses the original month and day numbers for {tblClient.YearEnd} but uses the year of the current date
    Then just datediff on e to get the number of days between the two dates
    I hope i understand your problem and that this helps
    Best regards
    Patrick

Maybe you are looking for

  • Exporting and importing without destroying masterfile

    Hi all. At my work, we are creating leaflets, brochures and other stuff like that, which need to be updated all the time in all different languages. In this case, i am the only one who does inDesign, where the others are in Acrobat. Is it possible fo

  • Problem in Standard Costing

    Dear Friends, When i am running standard cost estimate, indirect overheads are calculated from KP26. Suppose i have maintained the Machine Cost Rate at Rs. 60 for 1 Hour. When i run the standard cost estimate for that material, it is calculated by Rs

  • Where is JDK 1.4 beta?

    This used to be listed on the main page, but it's not there any more. It's not on the 'Early Releases' page either for some strange reason!

  • IMessage logged in but not working

    I recently had the logic board replaced on my early-2011 15" MacBook Pro due to video issues. While the machine was with Apple, I migrated my user to my wife's Mac and set up iCloud. I got my own computer back and had to re-login to iCloud (possibly

  • Intel chip design

    Hey guys I am kinda afraid that I might have the "Intel® Chipset Design Issue May Affect Certain HP Desktop and Notebook PCs" problem. Could you guys help me determine if I have it or not? My serial number is :5ch1140408 Do you guys need to know my p