PHP |计算剩余天数但考虑闰年

标签 php date

计算从今天开始的一个月剩余天数的小问题,我写的是:

$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

在这里查看https://3v4l.org/8ZhOb

在此处查看 DateTime 类文档 https://www.php.net/manual/en/class.datetime.php

关于PHP |计算剩余天数但考虑闰年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59953302/

相关文章:

javascript - 新浏览器选项卡或窗口中的 HTML

php - 私有(private)方法覆盖和可见性

php - 我的 PHP 包含数据库连接有什么问题?

php - strtotime() 使用 DD.MM.YY 输入返回当前日期 - 为什么?

Javascript 使用 datejs 解析 RFC3339 日期时间

vba - Excel 日期格式

php - 如何登录成功?

php - Laravel Spark : How to turn on Team Billing?

r - 如何在R中获取每月最后一个工作日的日期

php - 如何只显示当月的MySQL查询结果?