简体   繁体   English

添加跨年的天数时,strtotime 错误计算日期

[英]strtotime miscalculates date when adding days that cross year

I need to add days to a date.我需要在日期中添加天数。 I have been happily using the following and it's worked up until the end of the year:我一直很高兴地使用以下内容,并且一直使用到年底:

date('o-m-d', strtotime("{$start_date} +6 days"));

As an example, when $start_date equals 2022-12-19, the result is 2022-12-25:例如,当 $start_date 等于 2022-12-19 时,结果为 2022-12-25:

date('o-m-d', strtotime("2022-12-19 +6 days")); // 2022-12-25

This falls to pieces when the number of days lands on the first day of the year - so for 2022-12-26 the result is 2022-01-01 (2022, rather than 2023!)当天数落在一年的第一天时,这会变得支离破碎——因此对于 2022-12-26,结果是 2022-01-01(2022 年,而不是 2023 年!)

date('o-m-d', strtotime("2022-12-26 +6 days")); // 2022-01-01, which is incorrect!

Playing around I found it's only if the date lands on the first day of the year - here are some examples:玩弄我发现只有当日期落在一年的第一天时 - 这里有一些例子:

date('o-m-d', strtotime("2022-12-30 +1 days")); // 2022-12-31, correct
date('o-m-d', strtotime("2022-12-30 +2 days")); // 2022-01-01, incorrect!
date('o-m-d', strtotime("2022-12-30 +3 days")); // 2023-01-02, correct

date('o-m-d', strtotime("2023-01-03 -1 days")); // 2023-01-02, correct
date('o-m-d', strtotime("2023-01-03 -2 days")); // 2022-01-01, incorrect!
date('o-m-d', strtotime("2023-01-03 -3 days")); // 2022-12-31, correct

I've seen when I include the h:m:s, I get a weird time of day, but that would surely impact all the date calculations.我看到当我包含 h:m:s 时,一天中的时间很奇怪,但这肯定会影响所有日期计算。 Anyone have an idea what's going on here?任何人都知道这里发生了什么? (I'm using php@7.4) (我正在使用 php@7.4)

I've tried all sorts of variations, like adding the base date as the second parameter to strtotime, even trying relative to today (-11 days at time of writing) and always the same error..我尝试了各种变体,比如将基准日期作为第二个参数添加到 strtotime,甚至尝试相对于今天(撰写本文时为 -11 天),但总是出现相同的错误。

To be clear, adding two days to 2022-12-30 should result in 2023-01-01, not 2022-01-01.需要明确的是,在 2022-12-30 上加上两天应该是 2023-01-01,而不是 2022-01-01。

I've looked through other answers to similar questions, such as using我查看了类似问题的其他答案,例如使用

$date = new \DateTime('2022-12-26');
$end_date = date_add($date, date_interval_create_from_date_string("6 days"))->format('o-m-d');

which results in exactly the same error.这会导致完全相同的错误。

Use Y for the year, not o .使用Y表示年份,而不是o o is: o是:

ISO 8601 week-numbering year. ISO 8601 周编号年份。 This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead.这与 Y 具有相同的值,除了如果 ISO 周数 (W) 属于上一年或下一年,则使用那一年。

http://www.php.net/manual/en/datetime.format.php http://www.php.net/manual/en/datetime.format.php

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

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