gpt4 book ai didi

php - 格式化 DateTime Diff 以防止在 PHP 中显示 0 年 0 个月

转载 作者:行者123 更新时间:2023-11-29 02:19:31 25 4
gpt4 key购买 nike

我试图从数据库中找出今天日期和特定日期之间的差异。
我使用 DateTime Diff 来获取结果,它以 (years months and days) 格式为我提供了正确答案。唯一的问题是,如果差异小于一年,它会显示 0 年,这是不希望的。月和日相同。
是否可以检查这 3 个值中的任何一个是否为 0 或者是否有任何其他方法可以实现此目的?

这是我正在使用的代码-

$datetime1 = new DateTime($asset[$a]['PDate']);
$datetime2 = new DateTime("now");
$interval = $datetime1->diff($datetime2);
echo $interval->format('%y years %m months and %d days');

$datetime1 来自数据库,而 $datetime2 显示今天的日期。如果 $datetime1 类似于 12/9/2015 & %datetime2 是 12/3/2015 我得到的输出是 0 years 0 months and 6 days 而我希望它只显示 6天

最佳答案

所以检查格式如下:

if($datetime1->format('%y') != 0)
echo $datetime1->format('%y years %m months and ');
if($datetime1->format('%y') == 0 && $datetime1->format('%m') != 0)
echo $datetime1->format('%m months and ');
echo $datetime1->format('%d days');

或(重组):

if($datetime1->format('%y') != 0) {
echo $datetime1->format('%y years %m months and ');
} else {
if($datetime1->format('%m') != 0)
echo $datetime1->format('%m months and ');
}
echo $datetime1->format('%d days');

这将输出:

2年2个月零2天
2 个月零 2 天(如果 0 年)
2天(如果0年0月)
2年0个月零2天(如果是0个月)

如果月份的值为 0(与年份无关)则不应打印月份

$flag = false;
if($datetime1->format('%y') != 0) {
echo $datetime1->format('%y years ');
$flag= true;
}
if($datetime1->format('%m') != 0) {
echo $datetime1->format('%m months ');
$flag= true;
}
if($datetime1->format('%d') != 0) {
echo $flag?"and ":"";
echo $datetime1->format('%d days');
}

这将输出:

2年2个月零2天
2 个月零 2 天(如果 0 年)
2天(如果0年0月)
2年零2天(若为0个月)

关于php - 格式化 DateTime Diff 以防止在 PHP 中显示 0 年 0 个月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34058705/

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