如何通过PHP获得从今天到2011-5-20的天数?
可能重复:如何通过PHP获得从今天到2011-5-20的天数?,php,date,Php,Date,可能重复: 似乎只有一个javascript版本,那么PHP呢?计算它们之间的秒差,你就可以轻松地计算出天数 $oFirstDate = new DateTime($sDateFormat); $oSecondDate = new DateTime($sDateFormat2); $iSeconds = $oFirstDate->getTimeStamp() - $oSecondDate->getTimeStamp(); $iDays = $iSeconds / 60 / 60 /
似乎只有一个javascript版本,那么PHP呢?计算它们之间的秒差,你就可以轻松地计算出天数
$oFirstDate = new DateTime($sDateFormat);
$oSecondDate = new DateTime($sDateFormat2);
$iSeconds = $oFirstDate->getTimeStamp() - $oSecondDate->getTimeStamp();
$iDays = $iSeconds / 60 / 60 / 24;
我同意沙克蒂的观点;只需进行最小的更改,以下脚本就可以为您工作:
<?php
$datetime1 = date_create( date( 'Y-m-d' ) );
$datetime2 = date_create('2011-05-21');
$interval = date_diff($datetime1, $datetime2);
echo $interval->days . " days difference.";
好吧,我有一个通用的ish函数来处理这样的东西:
function timediffIn($time, $unit, $human = False){
$tokens = array (
'years' => 31536000,
'months' => 2592000,
'weeks' => 604800,
'days' => 86400,
'hours' => 3600,
'minutes' => 60,
'seconds' => 1
);
if(!array_key_exists($unit, $tokens)){
if ($human) print "No such unit: $unit\n";
return FALSE;
}
if(!strtotime($time)){
if ($human) print "$time does not translate into a valid time\n";
return FALSE;
}
$elapsed = time() - strtotime($time);
$interval = $tokens[$unit];
if($human){
print "It has been " . floor($elapsed / $interval) . " $unit since $time\n";
}
return floor($elapsed / $interval);
}
HTH几乎直接取自我几周前写的一篇文章:
@沙克蒂·辛格,我的问题是在今天和另一天之间数数,所以有点不同……没有区别。通过date('Y-m-d')
函数获取今天的日期可能重复:回答显然,“human”参数用于调试目的/命令行脚本-您可以安全地删除与之相关的所有内容。
$today = new DateTime();
$ref = new DateTime("2011-05-20");
$diff = $today->diff($ref);
echo "the difference is {$diff->days} days" . PHP_EOL;