获取星期,星期,月和年的日期

时间:2014-09-18 17:52:53

标签: mysql sql date

如果您只有MySQL的周日,周数,月份和年份,那么可以获得日期吗?

示例:

我想知道这个参数是哪一天:

  • 年份:2014
  • 月:9月(09)
  • 周数:37或9月的周数:3
  • 星期几:星期四

答案是' 2014-09-18'

2 个答案:

答案 0 :(得分:0)

使用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
;

Demo

注意
UNION生成从0到399的数字,因此我们可以生成年份的日历。现在我们可以应用您的其他约束,例如每周和每周的某一天。

答案 1 :(得分:0)

我在葡萄牙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

Portuguese Stack Overflow Answer Link:https://pt.stackoverflow.com/questions/33046/obter-data-com-dia-da-semana-n%C3%BAmero-da-semana-m%C3%AAs-e-ano/33063#33063

感谢所有帮助过我的人