PHP date()有问题-月份中的剩余天数
我试图计算一个月内从任何一天算起的剩余天数。我有以下代码:PHP date()有问题-月份中的剩余天数,php,date,timestamp,Php,Date,Timestamp,我试图计算一个月内从任何一天算起的剩余天数。我有以下代码: <?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 $day
<?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
我也尝试了date('d',$timestamp),但它仍然返回1表示当前日期,即使它应该是14。为什么我今天得到1分?谢谢
我的PHP版本是5.4.45。只需添加到timestamp变量,因为date函数需要第二个参数作为整数值。但当您提供格式化日期时,它被视为字符串
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
只需添加到timestamp变量,因为date函数需要第二个参数作为整数值。但当您提供格式化日期时,它被视为字符串
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可以简化这一过程:-
$now = new \DateTime();
$daysRemaining = (int)$now->format('t') - (int)$now->format('d');
.使用PHP使这一点更加简单:-
$now = new \DateTime();
$daysRemaining = (int)$now->format('t') - (int)$now->format('d');
.尝试使用
$timestamp=time()
代替$timestamp=date('Y-m-d')
改用DateTime
。尝试执行$timestamp=time()
而不是$timestamp=date('Y-m-d')
使用DateTime
。