Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the first Sunday of the month in MySQL?

Tags:

date

mysql

I did not find any of examples for MySQL - all of them were quite complicated.

How can I SELECT the first Sunday of the month?

like image 690
Aitvaras Avatar asked Feb 19 '23 12:02

Aitvaras


1 Answers

So choose the first day of the month: 2012-01-01 (or whatever month and year you want).

Get the weekday index of the date. Indexes here are from 0 to 6.

Subtract that index from 6 and you will get how many days you need to add until the date is Sunday.

Add that amount of days to the chosen day.

SELECT DATE_ADD("2012-01-01 10:00:00", INTERVAL (6 - WEEKDAY("2012-01-01 10:00:00")) DAY);

Or:

SELECT DATE_ADD("2012-01-01", INTERVAL (6 - WEEKDAY("2012-01-01")) DAY);
like image 127
Aitvaras Avatar answered Feb 22 '23 01:02

Aitvaras