Hi i would like to display Today if the given date is today else display countdown..
this is what i tried so far..it will always show nothing..what did i do wrong ?
$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':'');}
}
}
You use DateInteval object incorrectly
$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':'');}
}
This should do the trick:
<?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;
}
?>
Working demo here .
<?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 an object ...not correct $diff==0
This is a short and simple code which will probably solve your question.Try this:-
<?php
$d1 = date("Y-m-d");
$d2 = '2018-01-06';
if(strtotime($d1) == strtotime($d2) )
{
echo 'today';
}
else
{
printf('Countdown To Event : ');
}?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.