嗨我想显示今天,如果给定的日期是今天显示倒计时..
这是我到目前为止所尝试过的..它总是什么都不显示......我做错了什么?
$d1 = new DateTime(); // now
$d2 = new DateTime('2018-01-07'); // set the date +1 to compensate for 1-day
$diff = $d2->diff($d1);
list($y,$m,$d) = explode('-', $diff->format('%y-%m-%d'));
if ($d1 < $d2) {
$months = $y*12 + $m;
$weeks = floor($d/7);
$days = $d%7;
if($diff==0)
{
echo 'today';
}
else
{
printf('Countdown To Event : ');
if ($months) {printf('%d month%s ', $months, $months>1?'s':'');}
if ($weeks) {printf('%d week%s ', $weeks, $weeks>1?'s':'');}
if ($days) {printf('%d day%s ', $days, $days>1?'s':'');}
}
}
答案 0 :(得分:1)
您错误地使用DateInteval对象
$d1 = new DateTime(); // now
$d2 = new DateTime('2018-01-07'); // set the date +1 to compensate for 1-day
// Object of DateInterval class
$diff = $d2->diff($d1);
// Difference in days
$d = $diff->days;
if (! $d) {
echo 'today';
}
else {
$months = $diff->m;
$days = $diff->d;
printf('Countdown To Event : ');
if ($months) {printf('%d month%s ', $months, $months>1?'s':'');}
// if ($weeks) {printf('%d week%s ', $weeks, $weeks>1?'s':'');}
if ($days) {printf('%d day%s ', $days, $days>1?'s':'');}
}
答案 1 :(得分:1)
这应该可以解决问题:
<?php
$today = new DateTime();
$date = (new DateTime())->add(new DateInterval('P1D'));
if ($today->format('Y-m-d') === $date->format('Y-m-d')) {
echo 'TODAY';
} else {
$d = $today->diff($date);
$result = '';
if ($d->years > 1) {
$result .= $d->years.' Years | ';
} else if ($d->years == 1) {
$result .= '1 Year | ';
} else {
$result .= '0 Years | ';
}
if ($d->months > 1) {
$result .= $d->months.' Months | ';
} else if ($d->months == 1) {
$result .= '1 Month | ';
} else {
$result .= '0 Months | ';
}
if ($d->days > 1) {
$result .= $d->days.' Days';
} else if ($d->days == 1) {
$result .= '1 Day';
} else {
$result .= '0 Days';
}
echo $result;
}
?>
工作演示here。
答案 2 :(得分:0)
<?php
$d1 = new DateTime(); // now
$d2 = new DateTime('2019-01-08'); // set the date +1 to compensate for 1-
day
$diff = $d2->diff($d1);
list($y,$m,$d) = explode('-', $diff->format('%y-%m-%d'));
if ($d>0) {
$months = $y*12 + $m;
$weeks = floor($d/7);
$days = $d%7;
printf('Countdown To Event : ');
if ($months) {printf('%d month%s ', $months, $months>1?'s':'');}
if ($weeks) {printf('%d week%s ', $weeks, $weeks>1?'s':'');}
if ($days) {printf('%d day%s ', $days, $days>1?'s':'');}
}
else
{
echo "today";
}
$ diff是一个对象......不正确$ diff == 0
答案 3 :(得分:0)
这是一个简短而简单的代码,可能会解决您的问题。请尝试: -
<?php
$d1 = date("Y-m-d");
$d2 = '2018-01-06';
if(strtotime($d1) == strtotime($d2) )
{
echo 'today';
}
else
{
printf('Countdown To Event : ');
}?>