我有一个显示日期计数器的PHP代码到现在为止,我需要将每个数字放入span或div中,如下所示:
<div class="one">1</div> <div class="two">5</div> <div class="three">2</div> <div class="four">6</div>
我的代码:
<?php
function dateDiff($start, $end) {
$start = strtotime($start);
$end = strtotime($end);
$diff = $end - $start;
return round($diff / 86400);
}
echo dateDiff("2010-01-30", date('Y-m-d')).' d.' ;
?>
答案 0 :(得分:3)
使用DateTime
,非常简单
$d1 = new DateTime('2010-01-30');
$d2 = new DateTime(date('Y-m-d'));//use same format that was used in d1
$diff = $d2->diff($d1);
//code to display number of days into seperate digits
$str = "".$diff->days;
$size = strlen($str);
$i=0;
while($i<$size)
{
echo "<div>$str[$i]</div>";
$i++;
}
答案 1 :(得分:0)
查看http://www.php.net/manual/en/datetime.diff.php
$dStart = new DateTime('2010-01-30');
$dEnd = new DateTime(date('Y-m-d'));
$dDiff = $dStart->diff($dEnd);
$dDiff
将是DateInterval
对象,因此您可以执行此操作:
echo '<div class="year">' . $dDiff->y . '</div> <div class="month">' . $dDiff->m . '</div> <div class="day">' . $dDiff->d . '</div>';
我建议使用这种方法而不是自己计算这些值,因为很难准确计算出已经过了多少个月以及之后剩余多少天。
DateInterval
对象的属性days
也包含两个日期之间的全天数。用法:echo $dDiff->days;
PHP5.3 +必需。
答案 2 :(得分:-1)
<div class="year"><?php echo dateDiff("2010-01-30", date("Y")) ?></div>
<div class="month"><?php echo dateDiff("2010-01-30", date("m")) ?></div>
<div class="day"><?php echo dateDiff("2010-01-30", date("d")) ?></div>