您好,我想显示今天,如果给定的日期是今天,否则显示倒计时。
这就是我尝试过的,这样far..it就会一直告诉nothing..what我做错了吗?
$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':'');}
}
}发布于 2018-01-07 02:01:13
您错误地使用了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':'');}
}发布于 2018-01-07 02:26:43
这应该能起到作用:
<?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。
发布于 2018-01-07 02:14:00
<?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 is a object ...not correct $diff==0
(使用正确的对象创建正确的对象
https://stackoverflow.com/questions/48130010
复制相似问题