Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get friday last week in MYSQL

Tags:

mysql

How to get friday last week ?

I have tried code the folllowing, but it not forward not backward.

SELECT DATE_FORMAT(LAST_DAY(NOW()) - ((7 + WEEKDAY(LAST_DAY(NOW())) - 4) % 7), '%Y-%m-%d') last_friday;

The result that i need should be: 2013-05-24 not 2013-05-31.

Please change my coding.

like image 418
Jam Dara Avatar asked May 27 '13 07:05

Jam Dara


People also ask

How to get last friday date in MySQL?

Also 'dArc' gives the last Friday of the month using 'last_day', which the original post was using, so this may have been what the original question actually was.

How can I get last Friday of the month in MySQL?

Here is a simplified version using just date math: SELECT LAST_DAY(NOW()) - ((7 + WEEKDAY(LAST_DAY(NOW())) - 4) % 7);


2 Answers

Dude, try this one:

SELECT DATE_FORMAT(DATE_SUB(NOW(), INTERVAL ((7 + WEEKDAY(DATE_SUB(NOW(), INTERVAL 1 WEEK)) - 4) % 7) DAY), '%Y-%m-%d');
like image 96
KaeL Avatar answered Sep 17 '22 22:09

KaeL


In MySQL, the WEEKDAY function returns an integer from 0 to 6: 0 for Monday, 1 for Tuesday etc. If you take that value as the number of days and subtract it from the current date, i.e. like this:

NOW() - INTERVAL WEEKDAY(NOW()) DAY

you will always get the current [ISO] week's Monday.

Knowing that, you will only need to subtract 3 more days to get the last week's Friday. So, the final expression would go like this:

NOW() - INTERVAL WEEKDAY(NOW()) + 3 DAY

You can take a look at this SQL Fiddle demo as well.

like image 38
Andriy M Avatar answered Sep 20 '22 22:09

Andriy M