简体   繁体   中英

How to get the date of a day passed as Week Day Number? | mySQL

Wondering how this can be done..How to get the date of a day passed as Week Day Number from this week. For example if I pass 3 it will return Wed 4/20 . If I submit 1 it will return Monday 4/18 .

Essentially I need to do the opposite of SELECT WEEKDAY('2022-04-21');

By passing (3) to get the date 2022-04-21 as a response.

Can this accomplished in mySQL?

I think you probably want something like

SELECT DATE_ADD((CURDATE() - INTERVAL (WEEKDAY(CURDATE())) DAY), INTERVAL 3 DAY);

where you can replace the 3 near the end with your input.

CURDATE() gets you the current date, so (CURDATE() - INTERVAL (WEEKDAY(CURDATE())) DAY) gets you the start of the current week. The DATE_ADD function is then used to add your input parameter to the start of the current week.

This should be the opposite of the WEEKDAY function like you wanted.

Edited to add: I realize I mixed my syntaxes (using a - interval for subtracting the days and then using date_add for adding it back on). It would probably be cleaner to use one or the other. So:

SELECT CURDATE() - INTERVAL (WEEKDAY(CURDATE())) DAY + INTERVAL 3 DAY;

Edited based on comments: The answers above use your example of passing 3 to get Thursday (2022-04-21). If you want 0 to be a Sunday (and therefore 3 to be a Wednesday 2022-04-20), you can subtract one more.

So something like:

SELECT CURDATE() - INTERVAL (WEEKDAY(CURDATE())+1) DAY + INTERVAL 3 DAY

or

SELECT CURDATE() - INTERVAL (WEEKDAY(CURDATE())) DAY - Interval 1 DAY + INTERVAL 3 DAY

or even

SELECT CURDATE() - INTERVAL (WEEKDAY(CURDATE())) DAY + INTERVAL 3-1 DAY

where the 3 is your parameter and the -1 is constant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM