Skip to content
Advertisement

Get previous months first and last date

I need to query last month data from a database. So I need the first and last date of previous month to be able to make the “between” SQL query.

First date starts always from 1 of course, but hard coding it looks bad. Also hard coding the date format “dd-MM-yyyy” seems like a bad practise. Is there a simpler way to do this? Right now I have something amateurish but working, like this:

Advertisement

Answer

So I need the first and last date of previous month to be able to make the “between” SQL query.

You can do that computation directly in your database. In Oracle, you can get the first and last day of the previous month as dates like so:

In general, however, you don’t really need between and the last day. You can use half-open intervals – which is also safer, as it takes in account dates that belong to the last day of the month:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement