簡體   English   中英

獲取星期幾,星期幾,月份和年份的日期

[英]Get Date with Day of Week, Week Number, Month and Year

如果只有MySQL中的星期幾,星期幾,月份和年份,可以通過某種方式獲取日期?

例:

我想知道哪一天是這個參數:

  • 年:2014
  • 月:9月(09)
  • 年的周數:37或上月的周數:3
  • 星期幾:星期四

答案是“ 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM