Jayesh Shrimali Jayesh Shrimali - 1 month ago 7
PHP Question

Display date as "yesterday", "today" or "Tomorrow" when a birth date is inputted in PHP (Year doesn't matter)

In my PHP code, I am inputting a birth date.If current month and date happens to be the same as the month and date of the inputted birth date then it has to display

"it's my birthday"
.If current date is one day behind and month remains the same,then it has to display
"Tommorow"
and if the current date is one day ahead and month remains the same, then it has to display
"Yesterday"
.I have tried the following code

<?php
$datss = '11-10-1992';//a birth date
$yourDate = new DateTime($datss);
$yourDate->setTime(0, 0, 0);

$now = new DateTime();
$now->setTime(0, 0, 0);

$diff = $now->diff($yourDate);
$diffInDay = (int)$diff->format('%R%d%m');

if ($diffInDay == -1) {
echo 'yesterday ';
}
else if ($diffInDay == 0) {
echo "it's my birthday.";
}
else if ($diffInDay == +1) {
echo 'Tomorrow';
}

else{
echo '11-10-1992';
}
?>


It is echoing
"it's my birthday."
correctly when the birth date is given as
"$datss = 11-10-1992"
but when birth date is given as
$datss = '12-10-1992';
it is not echoing
'Tomorrow'
.

Answer

Please try the below given code

<?php

$yourDate = '12-10-1992';
$now =  'now';

//put the year data the same 
$yourDate = date('d-m-1970',strtotime($yourDate));
$now = date('d-m-1970',strtotime($now));

$diff = strtotime($yourDate) - strtotime($now);
$diffInDay= floor($diff/(60*60*24));    


if ($diffInDay == -1) {
    echo 'yesterday ';
}
else if ($diffInDay == 0) {
    echo "it's my birthday.";
}
else if ($diffInDay == +1) {
    echo 'Tomorrow';
}

else{
    echo '11-10-1992';
}

?>

Now if you give the birth date as '12-10-1992' it will print 'Tommorow' and if '10-10-1992' is given ,this will print as 'yesterday'.Also the year will not matter anymore ie if you give your birth date as '12-10-1993',it will still print as 'Tommorow'.

Comments