将日期换算为span或div

时间:2014-04-03 12:40:22

标签: php date

我有一个显示日期计数器的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.' ; 
?>

3 个答案:

答案 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>