Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get dates which are between last monday till current day?

Tags:

datetime

mysql

I am having dates in my database.

My database is in MySQL.

I want to fetch dates from my database which provides me dates from last monday till current day.

How can I do that?

like image 675
Parth Bhatt Avatar asked Apr 04 '11 10:04

Parth Bhatt


1 Answers

You first have to work out how many days ago last monday was, using the DAYOFWEEK function, then subtract that from the current date -

SELECT * from table
WHERE date >= DATE_SUB(CURDATE(),INTERVAL MOD(DAYOFWEEK(CURDATE())-2,7) DAY)
AND   date <= DATE_ADD(CURDATE(), INTERVAL MOD(7 - (DAYOFWEEK(CURDATE()) - 1), 7) DAY)

I'm not 100% sure about the +/- numbers here, you should be able to work it out from this though

EDIT: If this will only ever be run on the sunday at the end of the period, there is a much simpler version -

SELECT * from table
WHERE date >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
AND   date <= CURDATE()
like image 62
tobyodavies Avatar answered Oct 18 '22 05:10

tobyodavies