Oracle calculate the number of days between two dates, months and years

Reprinted from: https://www.cnblogs.com/AnneHan/p/4708386.html

The number of days between two dates in Oracle, the number of months and years:

One, heaven number:

In Oracle, directly subtract two dates, we can obtain the number of days;

1 select to_date('08/06/2015','mm/dd/yyyy')-to_date('07/01/2015','mm/dd/yyyy') from dual;

返回结果:36

Second, the number of months:

Calculate the number of months, need to use months_between function;

Copy the code
--Months_between 1 (date1, that represented by DATE2)    
2 - If the two dates in the same "day", or respectively, where the last day of the month, the result returned is an integer. Otherwise, the result returned will contain a fractional part (calculated as a 31-day month)      
. 3 SELECT MONTHS_BETWEEN (TO_DATE ('01 / 31 is /, 2015 ',' mm / dd / YYYY '), TO_DATE ('12 / 31 is /, 2014 ',' mm / dd / YYYY ')) "of MONTHS" the FROM the DUAL;       
. 4 returns the result:. 1       
. 5 SELECT MONTHS_BETWEEN (TO_DATE ('01 / 01 /, 2015', 'mm / dd / YYYY'), TO_DATE ('12 / 31/2014 ',' mm / dd / YYYY ')) "of MONTHS" the FROM the DUAL;       
. 6 returns the result: 0.032258064516129
Copy the code
Copy the code
1 select abs(trunc(months_between(sysdate , to_date('01/31/2015','mm/dd/yyyy'))))from dual;
2 select ceil(trunc(months_between(sysdate , to_date('01/31/2015','mm/dd/yyyy'))))from dual;
3 select floor(trunc(months_between(sysdate , to_date('01/31/2015','mm/dd/yyyy'))))from dual;
Copy the code

Three, years:

Calculate the number of years, it is calculated by the number of months, and then divided by 12; (there may be a better way, is not known)

1 select trunc(months_between(to_date('08/06/2015','mm/dd/yyyy'),to_date('08/06/2013','mm/dd/yyyy'))/12) from dual;
2 
3 --返回结果:2

Guess you like

Origin www.cnblogs.com/youyouqiao/p/12306281.html