gpt4 book ai didi

php - 2 月 1 日至 3 月 1 日之间的 laravel Carbon 差异不正确

转载 作者:行者123 更新时间:2023-12-02 20:32:56 25 4
gpt4 key购买 nike

当我使用 laravel Carbon 的 diffInMonths 时,我发现了一个奇怪的结果。谁能为我解释一下为什么它会这样工作。这是一个错误吗?以及如何使其正确。

$d1 = new Carbon('2018-02-01');
$d2 = new Carbon('2018-03-01');
dd($d1->diffInMonths($d2));

输出为:0(预期:1)

但是

$d1 = new Carbon('2018-02-02');
$d2 = new Carbon('2018-03-02');
dd($d1->diffInMonths($d2));

输出为:1

我的设置时区是“Asia/Ho_Chi_Minh”(GMT +7)。 PHP 版本 7.0.22。操作系统:Ubuntu Server 16.04

这个奇怪的结果只发生在 2 月 1 日到 3 月 1 日之间,其他月份的结果与预期一致。

我还尝试使用 date_diff 而不是 Carbon

$d1 = new \DateTime('2018-02-01');
$d2 = new \DateTime('2018-03-01');
$diff = date_diff($d1,$d2);
dump($diff->m);
dump($diff->d);
die;

它返回月份:0,天:28(不是预期的月份:1,天:0)

所以问题可能来自 PHP,而不是来自 Carbon。

最佳答案

非常奇怪的行为:

$jan = new Illuminate\Support\Carbon("2022-01-01");
$feb = new Illuminate\Support\Carbon("2022-02-01");
$mar = new Illuminate\Support\Carbon("2022-03-01");

$feb->diffInMonths($mar); // 0
$feb->floatDiffInMonths($mar); // 1.0

$jan->diffInMonths($mar); // 1
$jan->floatDiffInMonths($mar); // 2.0

解决方案

在 floatDiffInMonths 上使用 intval:

intval($feb->floatDiffInMonths($mar)); // 1
intval($jan->floatDiffInMonths($mar)); // 2

关于php - 2 月 1 日至 3 月 1 日之间的 laravel Carbon 差异不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48124152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com