如何将星期数转换为日期?

2021-11-20 00:00:00 datetime sql mysql

给定一年和日历周,我如何获得该周的星期二作为日期?

解决方案

假设您有 yearcw(日历周)作为变量(例如来自 SELECT 语句)你可以得到如下日期:

DATE_SUB(DATE_ADD(MAKEDATE(year, 1), INTERVAL cw WEEK),间隔工作日(DATE_ADD(MAKEDATE(year, 1), INTERVAL cw WEEK)) -1天),

短语DATE_ADD(MAKEDATE(year, 1), INTERVAL cw WEEK)重复;不想存储变量.SQL 语句在 MySQL 上非常适合我.

更新: 只是为了澄清:WEEKDAY(DATE_ADD(MAKEDATE(year, 1), INTERVAL cw WEEK)) 将产生一周的第一天.从中减去一个数字(-1 代表星期二;-2 代表星期三,依此类推,将为您选择一周中的特定日期).请参阅此处.>

Given a year and calendar week, how can I get the tuesday of that week as a date?

解决方案

Given you have year and cw (calender week) as variables (e.g. from a SELECT statement) you can get the DATE as following:

DATE_SUB(
  DATE_ADD(MAKEDATE(year, 1), INTERVAL cw WEEK),
  INTERVAL WEEKDAY(
    DATE_ADD(MAKEDATE(year, 1), INTERVAL cw WEEK)
  ) -1 DAY),

The phrase DATE_ADD(MAKEDATE(year, 1), INTERVAL cw WEEK) is duplicated; did not want to store a variable. The SQL-Statement worked nicely for me on MySQL.

UPDATE: Just for clarification: WEEKDAY(DATE_ADD(MAKEDATE(year, 1), INTERVAL cw WEEK)) will yield the first day of the week. Substracting a number from it (-1 for Tuesday; -2 for Wednesday and so forth will select a specific day in the week for you). See here.

相关文章