Date difference in months

How can I find the difference between two dates in months?
I assume I can't do this:
Date firstDate = 4/1/2000;
Date secondDate = 6/1/2002;
int monDiff = secondDate - firstDate;
Also is it better to use java date or sql date?
thx.

Here is a method that will compute the difference in years, months, and days. It's a bit more tricky that the previous post suggested when you take into account the day of the month. I'm not sure but I think that when you add a month to a date as in the suggested code you may have odd things happen when you go from Jan 31 to Feb to March since Feb may only have 28 days in it.
     * Compute the difference between two dates in years, months, and days.
     * The result is returned in a concatenated integer value of the form
     * ymmdd. So the difference between Apr 20, 2003 and Apr 15, 2025 would
     * be 211126 (21 years, 11 months, and 26 days) since 21 years and
     * 11 months gets you to May 20 2025, there are 31 days in May of 2025,
     * and it takes 25 days to go from May 20 2025 to April 15 2025! To split
     * the values off,
     * #years = return value / 10000,
     * #months = return value % 10000 / 100
     * #days = return value % 100.
     * This method will return a negative value if the 'from' value is after the
     * 'to' value (i.e. getDiff( from, to) = -getDiff( to, from )).
     * @param pFrom The time to compute the difference from.
     * @param pTo Date The time to compute the difference to.
     * @return int The differenct in the two dates in the form ymmdd.
    public static int getDiff( java.util.Date pFrom, java.util.Date pTo )
        int lMultiplier = 1;
        if ( pFrom.after( pTo ) );
            lMultiplier = -1;
            java.util.Date pTemp = pTo;
            pTo = pFrom;
            pFrom = pTemp;
        Calendar lFrom = new GregorianCalendar();
        lFrom.setTime( pFrom );
        Calendar lTo = new GregorianCalendar();
        lTo.setTime( pTo );
        int lFromYear = lFrom.get( Calendar.YEAR );
        int lFromMonth = lFrom.get( Calendar.MONTH );
        int lFromDay = lFrom.get( Calendar.DAY_OF_MONTH );
        int lToYear = lTo.get( Calendar.YEAR );
        int lToMonth = lTo.get( Calendar.MONTH );
        int lToDay = lTo.get( Calendar.DAY_OF_MONTH );
        int lYearDiff = lToYear - lFromYear;
        int lMonthDiff = lToMonth - lFromMonth;
        int lDayDiff = lToDay - lFromDay;
        if ( lDayDiff < 0 )
            lMonthDiff--;
            Calendar lTemp = new GregorianCalendar();
            lTemp.setTime( pTo );
            lTemp.add( lTemp.MONTH, -1 );
            lDayDiff = lTemp.getActualMaximum( lTemp.DAY_OF_MONTH ) + lDayDiff;
        if ( lMonthDiff < 0 )
            lYearDiff--;
            lMonthDiff = 12 + lMonthDiff;
        return lMultiplier * ( lYearDiff * 10000 + lMonthDiff * 100 + lDayDiff );
    }

Similar Messages

  • Date Difference in Months & Days using XSLT

    Hi,
    I have two dates and want to calculate how many months & days in between those using XSLT, do we have inbuilt functions to do the same?
    E.g. Start Date: 05/25/2014
           End Date: 12/31/2014
    Desired Output: 7 Months & 7 days (end date included in calculation)
    Thanks in advance.

    Hi,
    In XLST 2.0 (XPath 2.0) you can just use operator - to find difference between to dates, there's an example on link below...
    http://stackoverflow.com/questions/5544762/finding-the-difference-between-2-dates-in-xslt
    However, Oracle's implementation is not a full XSLT 2.0 (XPath 2.0), so it may not work... Please test it and let us know...
    <xsl:stylesheet version="2.0"
       xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
       xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns:my="my:my">
       <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:template match="/">
       <xsl:variable name="vDate1"
       select="my:dateFromUsDate(/*/d1)"/>
       <xsl:variable name="vDate2"
       select="my:dateFromUsDate(/*/d2)"/>
       <xsl:sequence select=
       "($vDate1 - $vDate2) div xs:dayTimeDuration('P1D')"/>
    </xsl:template>
    <xsl:function name="my:dateFromUsDate" as="xs:date">
      <xsl:param name="pUsDate" as="xs:string"/>
      <xsl:sequence select=
      "xs:date(concat(substring($pUsDate,7,4),
      substring($pUsDate,1,2),
      substring($pUsDate,4,2)
      "/>
    </xsl:function>
    </xsl:stylesheet>
    Cheers,
    Vlad

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

  • Difference between date to calculate months in BPEL

    Hello Team,
    I need your help to calculate Date difference between input date with current date and get the months in BPEL 2.0
    Please suggest.

    getting below error, input is xsd:date
    <bpelFault>
    <faultType>0</faultType>  
    <subLanguageExecutionFault>
    <part  name="summary">
    <summary>An error occurs while processing the XPath expression; the expression is xp20:month-from-dateTime(xp20:current-date()) - xp20:month-from-dateTime($inputVariable.payload/client:inputDt).</summary>  
    </part>
    <part  name="detail">
    <detail>XPath expression failed to execute. An error occurs while processing the XPath expression; the expression is xp20:month-from-dateTime(xp20:current-date()) - xp20:month-from-dateTime($inputVariable.payload/client:inputDt). The XPath expression failed to execute; the reason was: internal xpath error. Check the detailed root cause described in the exception message text and verify that the XPath query is correct. </detail>  
    </part>
    <part  name="code">
    <code>XPath expression failed to execute</code>  
    </part>
    </subLanguageExecutionFault>
    </bpelFault>

  • 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");

  • Date Difference in Oracle 10g

    Hi All,
    Am having two input parameter,
    1. Period Start Date
    2. Period End Date
    Now i need to find out the difference for the following parameters between those two dates,
    1. Monthly Difference (Number of months between two dates)
    2. Quaterly Difference (Number of quaters between two dates --> i.e 3 months difference)
    3. Weekly Difference (Number of weeks between two dates)
    4. Fortnightly Difference (Number of 15 days difference between two dates)
    Can anyone please help me out to achieve this?
    Thanks in advance.
    Regards,
    Sakthi.

    Oracle has a MONTHS_BETWEEN function. So that answers your first question.
    Everything else I would solve with arithmetic:
    select start_date
             , end_date
             , months_between(start_date, end_date) as month_diff
             , months_between(start_date, end_date)/3 as quarter_diff
             , (end_date-start_date)/7 as week_diff
             , (end_date-start_date)/15 as fortnight_diff
    from your_tableThese will all return fractions, so you may want to use FLOOR() or TRUNC() to return only integers.
    Cheers, APC

  • Calculate the date difference on essbase 9.3

    Hi Everbody,
    I want to calculate the difference between 2 date in essbase 9.3. Is any one did this practice ?
    I have done this but that is not a better way. so please share your thought with me.
    Regards
    Vikram Singh

    Hi,
    DateDiff function returns the difference (number) between two input dates in terms of the specified date-parts, following a standard Gregorian calendar.
    Syntax
    DateDiff ( date1, date2, date_part )
    date1+ is the number representing the input date between January 1, 1970 and Dec 31, 2037. The number is the number of seconds elapsed since midnight, January 1, 1970. To retrieve this number, use any of the following functions: Today(), TodateEx(), GetFirstDate(), GetLastDate(), DateRoll().
    Date-time attribute properties of a member can also be used to retrieve this number. For example,
    Product.currentmember.[Intro Date] returns the product introduction date for the current product in context.
    [Cola].[Intro Date] returns the product introduction date for Cola.
    date2+ A second input date. See date1.
    date_part+ Defined time components as per the standard calendar.
    DP_YEAR - Year of the input date.
    DP_QUARTER - Quarter of the input date.
    DP_MONTH - Month of the input date.
    DP_WEEK - Week of the input date.
    DP_DAY - Day of the input date.
    Edited by: Cnee on Jul 13, 2009 3:19 AM
    Edited by: Cnee on Jul 13, 2009 3:20 AM

  • SAP COPA Delivery and billing date difference

    Dear gurus,
    I am new to COPA and going on a COPA project.
    Here is one question that I have been searching answer for.
    At the month end reconciliation of FI COPA data, there could be a situtaion where the SD delivery takes place this month but the billing for the same happens next month. under this circumstance,
    1. how would a busness like to see the data?
    2. Is there a way to reconcile the data where there is such date difference to get the correct report?
    regards
    Roy

    Hi Roy
    This is often a problem and causes FI/COPA to be out of synch....
    However, please note that, this situation can also be a genuine one due to legal restrictions.. In some countries, you can not recognize revenue till customer gives you Proof of Delivery (POD)... In such cases, the PGI cost hits P&L in Month X and revenue hits P&L in Month X+1
    To avoid this situation, you have 2 options....Both are tried and tested approaches
    1. Use Exit RV60AFZB and write ABAP code saying that billing month cant be different than PGI month... This approach can be used if you are not bound by the legal restrictions I said above
    2. Another approach is to use accrual keys in your SD pricing procedure.. (Ask your SD guy to do this)
    a. At PGI: The accounting entry would be
    Stock issued, but not Billed a/c ........... Dr (This is also a balance sheet account)
    Stock /ac ............................................Cr (This is a Balance sheet acount)
    b. During Billing, the entry would be
    Customer .................................. Dr
    Revenue ....................................Cr
    COGS ..........................................Dr
    Stock issued, but not Billed a/c.....Cr
    This way, COGS and Revenue are both accounted in same month
    BR,Ajay M

  • Date Difference in Words

    Hi,
    Want to display the date difference in the following format..
    3 years 2 months 1 days like this.
    Can anybody help me on this..
    Thanks..

    SQL Statement which produced this data:
      SELECT (( (TO_CHAR (TO_DATE (:P_DATE1), 'YYYY')
                      - TO_CHAR (TO_DATE (:P_DATE2), 'YYYY'))
                     || ' Years ')
                     || (ROUND (
                           MONTHS_BETWEEN (TO_DATE (:P_DATE1, 'DD-MM-YYYY'),
                                           TO_DATE (:P_DATE2, 'DD-MM-YYYY')))
                     || ' Months ')
                     || (  TO_DATE (:P_DATE1, 'DD-MM-YYYY')
                         - TO_DATE (:P_DATE2, 'DD-MM-YYYY')
                         || ' Days')
                        )          AS DIFFERENCE
        FROM DUAL
    "DIFFERENCE"
    '1 Year 12 Months 365 Days' Input for the following data :p_date1 is sydate  :p_date2 is '31-05-2012' Edited by: Archana D on May 31, 2013 11:34 AM
    -Added the input parameter values

  • Date difference when converting Calendar date to sql date

    I am trying to convert a Calendar date to sql date. The only problem in the conversion is sql date adds 1 month to the original date. Due to this my query results show different data than what it is suppossed to show.
    Here is my code
    Calendar startDate = Calendar.getInstance();
    startDate.set(2006, 10, 01, 00, 00); // 1-Oct-2006
    return (new java.sql.Date(date.getTimeInMillis()));
    on the last statement it adds a month to original date. So the final date i get is 1-Nov-2006.
    Any solution to this problem?
    Thanks
    Sameer

    Thanks everyone for quick response.
    I have read javadocs many times but that does not
    change the fact that Calendar and Sql date
    interpretation is different.No, it isn't. You are setting the moth to november when you set the month to 10, and november is what java.sql.Date is showing. So where is the difference? You are doing it wrong and that is why you get the wrong month.
    How the f do you think that the calender should know that you want october when you set it to november?
    My application is deployed through web service and
    the clients may access it through any programming
    langague (java, php, ec). Even I am testing it
    through java and php. Still doesn't matter. You need to subtract the month by one if you want to let your user use 1 for january.
    While testing it through java month is different but
    through php its correct.Read the docs.
    Can smoeone please give me the best possibel solution
    to this?see above

  • Query Date Difference

    I have the data format in the customer contact table as DD/MM/YYYY
    ex. 11/10/1981
    how can i write SQL for calculate date difference from that date in table until now(SYSDATE) to know that
    how long they be my customer ?
    in format yy years mm month dd days
    ex. 15 years 3 month 12 day
    I have created this query....
    SELECT customer_id, first_name ,cust_date,
    TRUNC((TRUNC (sysdate)-cust_date)/365)| |' years '||
    TRUNC(MOD(TRUNC(sysdate)-cust_date,365))||' days 'AS MDATE FROM Customer;
    but it show only years and date...
    ex. 31 years 165 days
    how can i calculate for result "31 years X month Y day" ?

    Here's a starting point...
    SQL> select sysdate, sysdate - 1234 from dual
      2  /
    SYSDATE   SYSDATE-1
    09-AUG-06 24-MAR-03
    SQL> select trunc(trunc(months_between (sysdate, sysdate - 1234))/12) yrs,
      2  mod(trunc(months_between(sysdate, sysdate - 1234)), 12) mnths,
      3  sysdate - add_months((sysdate - 1234), trunc(months_between(sysdate, sysdate - 1234))) dys
      4  from dual
      5  /
           YRS      MNTHS        DYS
             3          4         16
    SQL> Edited by: BluShadow on Nov 24, 2008 3:51 PM
    Darn it! way too slow. :D

  • Fm date interval to months

    Hi experts,
    i need a fm to convert the interval of two dates into months.
    I have found  RH_PM_CONVERT_DATE_TO_MONTH
    for this. But i couldnt make it work from se37.
    Can u help me ? Anyone can u make it work and say these are the parameters to enter.
    Or u can tell me another fm for this
    Thanks alot

    hi check this..
    REPORT ZDATEDIFF.
    DATA: EDAYS   LIKE VTBBEWE-ATAGE,
          EMONTHS LIKE VTBBEWE-ATAGE,
          EYEARS  LIKE VTBBEWE-ATAGE.
    PARAMETERS: FROMDATE LIKE VTBBEWE-DBERVON,
                TODATE   LIKE VTBBEWE-DBERBIS DEFAULT SY-DATUM.
    call function 'FIMA_DAYS_AND_MONTHS_AND_YEARS'
      exporting
        i_date_from          = FROMDATE
        i_date_to            = TODATE
      I_FLG_SEPARATE       = ' '
      IMPORTING
        E_DAYS               = EDAYS
        E_MONTHS             = EMONTHS
        E_YEARS              = EYEARS.
    WRITE:/ 'Difference in Days   ', EDAYS.
    WRITE:/ 'Difference in Months ', EMONTHS.
    WRITE:/ 'Difference in Years  ', EYEARS.
    INITIALIZATION.
    FROMDATE = SY-DATUM - 60.

  • Have family plan with 250 data which I almost use each month.  Going on vacation and will be on the road for two weeks.  Should I up my data for a month then change back.  Is it worth it or should I just run over and pay the extra 15 per gig?

    have family plan with 250 data which I almost use each month.  Going on vacation and will be on the road for two weeks.  Should I up my data for a month then change back.  Is it worth it or should I just run over and pay the extra 15 per gig?

    Hello mlazaretti. Vacation time is awesome. (Especially a road trip!) Since you will be going out for two weeks, you never know if having extra data may come in handy. I highly recommend switching to the next tier up so this way you have more data. This way it is only $10.00 more versus $15.00, and you dont have to worry about overages. Then change back at the start of the next billing cycle.
    If you need help making this change let us know! Have a safe trip!
    NicandroN_VZW
    Follow us on twitter @VZWSupport

  • Be careful if you change your Data Plan mid month to save money.

    I have been contacted two times now by phone by Verizon representatives that were overwhelmingly concerned about the amount of money I was spending on my monthly cell phone bill.  Their solution, both times, was for me to switch to a different data plan for the month if I see that I am going to run over my allowance.  For the past few months, I had switched my account to the 6 GB plan because I knew that there was a potential for me to run over because of some work that I was doing.  On the 14th of February I looked at my usage and we had only used 2 GB of data for the month and only had 6 days left in my cycle so I decided to switch back to the 4 GB plan to save money.  Remember, this methodology was recommended by Verizon themselves to save money.
    Lets do some math.  I have used ~2 GB of data on a 6 GB plan.  I switched back to the 4 GB plan with only 6 days left in my cycle.  Anyone with any math skills at all would see that I should have ~2 GB of data to use.  This is not the case with Verizon.  AFTER SWITCHING, I was informed that I only had 0.9 GB of data left because they had prorated my data plan.  It is pertinent to mention at this point that you can only switch one time in a month.  Guess what?  I ran over.  Now it is going to cost me more than it would have because I followed their suggestion.  The worst part is, I will be paying more for the 4 GB plan (with the overrun) than I would have had I left it at the 6 GB plan and for the cycle I will only have used ~ 3 GB of data.  Somehow it almost seems illegal to sell someone 4 GB of data and charge them an overage fee for using 3 GB.
    I called Verizon about this and was very politely told, "So what? and is there anything else I can help you with?"  If this isn't a rouse to make money, there has never been one.
    If a Verizon rep reads this and would like to assist, I would be grateful, but I doubt anyone even cares.  Hank Williams said it best, "I was gettin' s******, but I wasn't gettin' kissed."
    Benny

    BigRedGonzo wrote:
    It asked if I wanted to make the change retroactive to the beginning of the cycle.  I told it I did.  What since would it make to not do so?
    Not sure. The only thing I can think of is if you changed it after the billing cycle closed on the time period where you had the overages.

  • My calendar on my iPhone 4 erases all data over a month old except for recurring events.  How Do I get it to keep the info and not erase calendar events?

    My calendar on my iPhone 4 erases all data over a month old except for recurring events.  How Do I get it to keep the info and not erase calendar events?

    Settings>Mail, Contacts, Calendars>Calendars>Sync>All Events.
    Note: If you're using a work Exchange account, the administrator my have restricted your options for this setting.

Maybe you are looking for