简体   繁体   中英

how to calculate days until next birthday using php

I have 2 input fields for birth dates. I would like to then calculate days until the next birthday for each individual and the difference between both dates entered to determine who is older. Is my syntax logical/where did i go wrong?

 <form> John's Birthday (YYYY-MM-DD): <input type=text name=jhbd value=0><br> Jake's Birthday (YYYY-MM-DD): <input type=text name=jkbd value=0><br> <input type=submit> </form>

$john_bd = $_POST['jhbd'];
$jake_bd = $_POST['jkbd'];

$today = date("Y/m/d");
$interval_jh = $john_bd ->diff($today);
$interval_jk = $jake_bd ->diff($today);

echo "There are".$interval_jh->days."days until John's birthday ";
echo "There are".$interval_jk->days."days until Jake's birthday ";

if ($john_bd > $jake_bd) {
   echo "John is older";
} else if ($jake_bd > $john_bd) {
   echo "Jake is older";
} else {
   echo "Both Jake and John are twins!";
}

You need to convert them first.

 $today = time(); 
 $your_date = strtotime($john_bd);
 $datediff = $now - $john_bd;
 echo floor($datediff/(60*60*24));

it might help you

Your variant is almost correct. Use format for show diff between dates. Like in example

$origin = new DateTime('2009-10-11');
$target = new DateTime('2009-10-13');
$interval = $origin->diff($target);
echo $interval->format('%R%a days');
public function days_to_birth(string $date) : int  {
    if(empty($date))          
    {
        return -1;
    }
    
    if($date == '0000-00-00') 
    {
        return -1;
    }

    $ts = strtotime($date.' 00:00:00');
    $bY = date('Y',$ts);
    $bm = date('m',$ts);
    $bd = date('d',$ts);

    $nowY = date('Y');
    $nowm = date('m');
    $nowd = date('d');

                            
    if($bm == $nowm && $bd >= $nowd)                        
    {
        return $bd - $nowd;
    }

    if( ($bm == $nowm && $bd < $nowd) || ($bm < $nowm) )
    {
        $nextBirth = ($nowY+1).'-'.$bm.'-'.$bd;
        $nextBirthTs = strtotime($nextBirth);
        $diff = $nextBirthTs - time();
        return floor($diff/(60*60*24));
    }

    if($bm > $nowm )                        
    {              
        $nextBirth = $nowY.'-'.$bm.'-'.$bd.'00:00:00';
        $diff = strtotime($nextBirth) - time();
        return floor($diff/(60*60*24));
    }

    return -1;                                      
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM