简体   繁体   English

查找给定周数周期的最接近的未来日期

[英]Find closest, future date of given number of weeks cycle

Let's say I have a:假设我有一个:

start_date = '2020-01-06'

and date(now())date(now())

And I want to find closest future date, starting from now that is a multiplication of 4 (n) (or another number) weeks cycle from start_date我想找到最接近的未来日期,从现在开始,从start_date开始乘以 4 (n)(或其他数字)周周期

Expected output as for today would be '2020-03-02'今天的预期产量为'2020-03-02'

I can't came up with any smart idea to check for it.我想不出任何聪明的主意来检查它。

I'll highly appreciate any suggestions.我将非常感谢任何建议。

You could do date arithmetics:你可以做日期算术:

  • compute the difference between now and the "anchor" date计算现在和“锚”日期之间的差异
  • divide that by 7 (days per week) and 4 (weeks)将其除以 7(每周天数)和 4(周数)
  • take the next integer value from the result从结果中取出下一个整数值
  • multiply by 4 and 7, then add that number of days to the current date乘以 4 和 7,然后将该天数添加到当前日期

In SQL:在 SQL 中:

date'2020-01-06' + ceil((current_date - date'2020-01-06')::numeric / 4 / 7)::int * 4 * 7

Dremo on DB Fiddlde : DB Fiddlde 上的 Dremo

with t as (select date'2020-01-06' anchor, 4 n)
select 
    anchor,
    n,
    current_date,
    anchor + ceil((current_date - anchor)::numeric / n / 7)::int * n * 7 next_date
from t
anchor     |  n | current_date | next_date 
:--------- | -: | :----------- | :---------
2020-01-06 |  4 | 2020-02-10   | 2020-03-02

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM