简体   繁体   中英

Dateadd and Datediff function in oracle

I want to use Oracle but DATEDIFF and DATEADD function doesn't work in Oracle DB.

How to write below mentioned code in Oracle?

datediff('QUARTER', pr.StartDate, SYSDATE)

datediff('MONTH', pr.StartDate, SYSDATE)

The best thing to do in this case is to use Oracle's MONTHS_BETWEEN() function.

Instead of:

datediff('QUARTER', pr.StartDate, SYSDATE)

you would use:

MONTHS_BETWEEN(pr.startdate, SYSDATE) / 3

and instead of:

datediff('MONTH', pr.StartDate, SYSDATE)

you would use:

MONTHS_BETWEEN(pr.startdate, SYSDATE)

Keep in mind that MONTHS_BETWEEN() will return fractions of months, so use TRUNC() or ROUND() if you need an integer number.

Of course, if you need days instead of months, you can simply subtract one date from another, eg, SYSDATE - pr.startdate or vice-versa.

If you need to add days to a date, you can simply to this:

pr.startdate + 1 -- where 1 is the number of days

And if you need to add or subtract months, use the ADD_MONTHS() function - unlike INTERVAL s this function is safe to use in leap years.

Hope this helps.

These do not have simple exact equivalents because of the semantics of datediff() . It counts the number of "boundaries" between two date/times.

I believe these are semantically equivalent:

trunc(months_between(trunc(pr.StartDate, 'Q'), trunc(sysdate, 'Q')) / 3)
months_between(trunc(pr.StartDate, 'MONTH'), trunc(sysdate, 'MONTH'))

Because of the truncation to the first day of the quarter/month, these should not be returning fractions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM