![](/img/trans.png)
[英]MySQL: Get date based on the nth day of the week on a particular month/year
[英]Get Date with Day of Week, Week Number, Month and Year
如果只有MySQL中的星期几,星期几,月份和年份,可以通过某种方式获取日期?
例:
我想知道哪一天是这个参数:
答案是“ 2014-09-18”
使用Barmars建议,您可以即时建立年度日历,并对照您的限制对其进行检查:
SET @year := 2014; -- set the year of the constraints
SET @week := 37; -- the week
SET @day_of_week := 5; -- the day of the week (numerical)
-- build the first of the wanted year as supposed by Barmar
SET @first_of_year = STR_TO_DATE(CONCAT(@year, '-01-01'), '%Y-%m-%d');
SELECT
@first_of_year + INTERVAL t.n DAY the_date
FROM (
SELECT
a.N + b.N * 10 + c.N * 100 AS n
FROM
(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3) c
ORDER BY n
) t
WHERE
t.n < TIMESTAMPDIFF(DAY, @first_of_year, @first_of_year + INTERVAL 1 YEAR)
AND
WEEK(@first_of_year + INTERVAL t.n DAY) = @week
AND
DAYOFWEEK(@first_of_year + INTERVAL t.n DAY) = @day_of_week
;
注意
UNION会生成0到399之间的数字,因此我们可以生成年份的日历。 现在,我们可以应用您的其他约束条件,例如一年中的某周和一周中的某天。
我在葡萄牙语Stake Overflow中问了同样的问题,他们找到了一个简单的解决方案。
使用str_to_date,年,周号和星期几。
%Y Year, numeric, four digits
%U Week (00..53), where Sunday is the first day of the week
%W Weekday name (Sunday..Saturday)
SELECT str_to_date('201437 Thursday', '%Y%U %W');
结果:
2014-09-18 00:00:00
葡萄牙语堆栈溢出答案链接: https : //pt.stackoverflow.com/questions/33046/obter-data-com-dia-da-semana-n%C3%BAmero-da-semana-m%C3%AAs-e- ano / 33063#33063
感谢所有帮助我的人
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.