Get the number of days between two dates in Oracle, inclusive of the dates
Asked Answered
F

1

13

I want to get total number of days between two provided dates. I've tried the below query but didn't get the exact different; the last date is not being included.

select (to_date ('15-06-13','dd-MM-yyyy') - to_date('01-02-12','dd-MM-yyyy')) 
  from dual

This should return 501 days but it is returning 500 days instead. If I add +1 after calculation, then I'm getting the correct result.

Do I really need to include +1 or is there an alternate approach to get the actual result?

Felicidadfelicie answered 21/12, 2013 at 17:6 Comment(3)
It's returning 500 days because that is the difference :-). If you want it to return 1 more than the difference then you should add 1, yes.Tranquilizer
@Ben: I would say it is not adding end date (i.e. 15-06-13) or start date (01-02-12). I dont wanna add one day. Refer this link timeanddate.com/date/…Felicidadfelicie
The link says "Include end date in calculation (1 day is added)"; it's explicitly telling you that 1 day will be added. It's just not the default behaviour of subtraction to do what you're asking, 10 - 4 is 6, not 5. If you want to change the default behaviour you will have to do so manually.Tranquilizer
L
19

In Oracle substracting two dates returns the number of days between two dates.
A minus operator works in the same way as for numbers:

20 - 20 = 0   ===>      2013-05-20  -  2013-05-20 = 0
25 - 20 = 5   ===>      2013-05-25  -  2013-05-20 = 5

If you want to include last number or last date, you need to add 1:

20 - 20 + 1 = 1   ===>      2013-05-20  -  2013-05-20  + 1 = 1
25 - 20 + 1 = 6   ===>      2013-05-25  -  2013-05-20  + 1 = 6
Laporte answered 21/12, 2013 at 19:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.