如何将星期几(DOW)转换为当前周的对应日期?
问题:如何将星期几(DOW)转换为给定周的对应日期?
我已经知道怎么从日期里提取星期几(DOW)了,比如执行SQL:SELECT EXTRACT(DOW FROM '2018-04-23'::date)。但现在想做逆操作:怎么把一系列DOW值转换成**给定周(相对于当前周)**的对应日期?示例数据如下:
| id | the_dow |
|---|---|
| 358 | 1 |
| 359 | 2 |
| 360 | 5 |
| 361 | 2 |
| 362 | 3 |
回答
嘿,刚好PostgreSQL里有现成的函数组合能搞定这个,我给你一步步说清楚:
核心思路
先找到目标周的基准日期(比如当前周的周日,因为PostgreSQL的DOW定义是0=周日、1=周一……6=周六),然后给基准日期加上the_dow对应的天数偏移,就能得到目标日期。
1. 转换为当前周的对应日期
用date_trunc('week', current_date)可以获取当前周的起始周日(默认行为,和DOW定义匹配),然后直接加上the_dow天即可:
SELECT id, the_dow, -- 直接把基准日期+DOW值转成date类型 (date_trunc('week', current_date) + the_dow)::date AS current_week_date FROM your_table;
举个例子:如果当前周的起始周日是2024-05-19,那the_dow=1会得到2024-05-20(周一),the_dow=5会得到2024-05-24(周五),完全符合你的需求。
2. 转换为相对当前周的其他周(上周/下周)
只需要给基准日期加上周偏移即可,比如上周就减1周,下周就加1周:
上周的对应日期
SELECT id, the_dow, (date_trunc('week', current_date) - INTERVAL '1 week' + the_dow)::date AS last_week_date FROM your_table;
下周的对应日期
SELECT id, the_dow, (date_trunc('week', current_date) + INTERVAL '1 week' + the_dow)::date AS next_week_date FROM your_table;
注意:如果你的DOW是ISO周定义(1=周一,7=周日)
如果你的the_dow遵循ISO周规则(1=周一,7=周日),需要先把7转换成0(匹配PostgreSQL的DOW),再计算:
SELECT id, the_dow, (date_trunc('week', current_date) + CASE WHEN the_dow =7 THEN 0 ELSE the_dow END)::date AS current_week_date FROM your_table;
或者如果你想直接用ISO周的周一作为基准,用date_trunc('iso_week', current_date)(返回当前ISO周的周一),然后加the_dow-1天:
SELECT id, the_dow, (date_trunc('iso_week', current_date) + (the_dow -1))::date AS iso_week_date FROM your_table;
内容的提问来源于stack exchange,提问作者ere
相关产品推荐
相关产品推荐

