php date()的麻烦 - 月份的剩余天数



我正在尝试计算从任何一天开始的一个月内的剩余天数。我有以下代码:

<?php
date_default_timezone_set("UTC");
echo $timestamp = date('Y-m-d');
echo " - ";
echo $daysInMonth = (int)date('t', $timestamp);
echo " - ";
echo $thisDayInMonth = (int)date('j', $timestamp);
echo " - ";
echo $daysRemaining = $daysInMonth - $thisDayInMonth;
?>

输出是:2016-12-14-31-1-30

我也尝试了日期('d',$ timestamp),但是现在仍然返回1个,即使应该是14岁。为什么今天我要获得1个?谢谢。

我的PHP版本是5.4.45。

只需将strtime添加到时间戳变量,因为日期函数需要第二个参数作为整数值。但是,当您提供格式的日期时,它被认为是字符串。

date_default_timezone_set("UTC");
echo $timestamp = date('Y-m-d');
echo " - ";
echo $daysInMonth = (int)date('t', strtotime($timestamp));
echo " - ";
echo $thisDayInMonth = (int)date('j', strtotime($timestamp));
echo " - ";
echo $daysRemaining = $daysInMonth - $thisDayInMonth;

输出:

2016-12-14 - 31 - 14 - 17

使用PHP的DateTime类,使它变得更简单: -

$now = new DateTime();
$daysRemaining = (int)$now->format('t') - (int)$now->format('d');

看到它有效。

最新更新