2

有没有人有一段 MYSQL 代码可以给我未来一年的新日期时间,即一周中的同一天?

SELECT new_day = ADDDATE(new_day,INTERVAL 364 DAY) FROM my_table

适用于非闰年。任何想法如何最好地处理闰年?

4

3 回答 3

3

鉴于正常年份是 52 周零 1 天,闰年是 52 周零 2 天,您的新日期将比旧年早一到两天。对于平年元旦之后的任何日期,或闰年 1 月 2 日之后的任何日期,加上 52 周或 364 天后,您将得到下一年的日期,该日期与一周的同一天发生本月前 1 天或 2 天(或上个月末)。

这给您留下了如何处理一年中的前两天的问题。大概“明年”是至关重要的,所以 2013-12-31 比 2013-01-01 晚 52 周的简单答案是不正确的。在这种情况下,您必须编写一个条件表达式,用 SQL 拼写为 CASE。

SELECT CASE WHEN YEAR(DATEADD(ref_date, INTERVAL 364 DAY)) = YEAR(ref_date)
       THEN DATEADD(ref_date, INTERVAL 371 DAY)
       ELSE DATEADD(ref_date, INTERVAL 364 DAY)
       END
  FROM ...wherever...
于 2013-01-13T16:02:15.913 回答
1

how do you wish it to deal with leap years? either save month and date and compare if 364 or 371 are closest to first day, and pick regardingly, or do nothing and face inaccuracy after a couple of years.

  • *saved_date* is the very first date before created new dates based on it
  • *passed_years* is increasing for every new since the first

    date_add(last_date, INTERVAL (case when datediff(date_add(saved_date, INTERVAL passed_years YEAR), date_add(last_date, INTERVAL 371 DAY)) <= 3 then 371 else 364 end)) DAY)

The idea of this is to either fetch 52 or 53 weeks of the next year. leap years doesn't affect weekdays, but they "contribute" to an already existing problem; the date gets lower for each passing year if you only add 52 weeks each year without above solution.

于 2013-01-13T15:32:09.857 回答
0

为什么不简单

CURDATE() + INTERVAL 52 WEEK`

当然,它会在“日历”中提前 1 或 2 天。

mysql> SELECT NOW(), CURDATE() + INTERVAL 52 WEEK;
+---------------------+------------------------------+
| NOW()               | CURDATE() + INTERVAL 52 WEEK |
+---------------------+------------------------------+
| 2017-09-05 15:50:46 | 2018-09-04                   |
+---------------------+------------------------------+

如果您需要它“稍后”,请使用53.

于 2017-09-05T22:51:50.057 回答