计算从今天开始的一个月剩余天数的小问题,我写的是:
$today = date('Y/m/d');
$timestamp = strtotime($today);
$daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
echo $daysRemaining;
我得到了剩余的天数
为了进行测试,我输入了二月份的静态日期
$timestamp = strtotime('2020-02-01');
$daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
echo $daysRemaining;
问题是,考虑到闰年,我如何计算该月的剩余天数,例如 2020 年 2 月将有 29 天,这样我就可以摆脱剩余的 28 天
最佳答案
停止使用函数并开始使用 DateTime 类!!! 这段代码应该可以解释清楚。
<?php
$x = new DateTime('2020-02-17'); // create your date
$y = clone $x; // copy the date
$y->modify('last day of this month'); // alter the copy to the last day
echo $x->format('d') . "\n"; // show the day of the first date
echo $y->format('d') . "\n"; // show the day of the second date
echo $y->format('d') - $x->format('d'); // show the difference between the two
输出:
17
29
12
在此处查看 DateTime 类文档 https://www.php.net/manual/en/class.datetime.php
关于PHP |计算剩余天数但考虑闰年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59953302/