Sunday, February 9, 2014

Function to Get Year Month & Days for given Start Date and End Date

CREATE OR REPLACE FUNCTION xx_get_year_month_day_f (l_date_start    DATE,
                                                    l_date_end      DATE)
   RETURN VARCHAR2
AS
   l_months_between      NUMBER := 0;
   l_months              NUMBER := 0;
   l_tot_months          NUMBER := 0;
   l_years               NUMBER := 0;
   l_days                NUMBER := 0;
   l_no_days_month_end   NUMBER := 0;
BEGIN
   IF l_date_start > l_date_end
   THEN
      RETURN 'Enter Proper Dates !!!';
   END IF;

   l_months_between := TRUNC (MONTHS_BETWEEN (l_date_end, l_date_start));

   DBMS_OUTPUT.put_line ('l_months_between: ' || l_months_between);

   l_years := FLOOR (l_months_between / 12);

   DBMS_OUTPUT.put_line ('l_years: ' || l_years);

   l_months :=
      FLOOR (
         MONTHS_BETWEEN (l_date_end,
                         ADD_MONTHS (l_date_start, (l_years * 12))));
   DBMS_OUTPUT.put_line ('l_months: ' || l_months);


   l_tot_months := (l_years * 12) + l_months;

   DBMS_OUTPUT.put_line ('l_tot_months: ' || l_tot_months);

   l_days :=
      fffunc.
       days_between (l_date_end, ADD_MONTHS (l_date_start, l_tot_months))
      + 1;

   DBMS_OUTPUT.put_line ('l_days: ' || l_days);

   l_no_days_month_end :=
      (  TRUNC (ADD_MONTHS (l_date_end, 1), 'MM')
       - 1
       - TRUNC (l_date_end, 'MON'))
      + 1;

   DBMS_OUTPUT.put_line ('l_no_days_month_end: ' || l_no_days_month_end);

   IF l_days >= l_no_days_month_end
   THEN
      l_days := 0;
      l_months := l_months + 1;
   END IF;

   IF l_months = 12
   THEN
      l_days := 0;
      l_months := 0;
      l_years := l_years + 1;
   END IF;


   RETURN    l_years
          || ' Years(s) '
          || l_months
          || ' Month(s) & '
          || l_days
          || ' Day(s)';
EXCEPTION
   WHEN OTHERS
   THEN
      DBMS_OUTPUT.put_line ('Main Exception: ' || SQLERRM);
      RETURN NULL;
END;

No comments:

Post a Comment