skip to Main Content

i have 3 variables with 3 numbers (day, year, month)
they all become together to a date type variable.
also, i have a date variable with the current day.

how do i check if the first date is 13 or less years before the current one?
here’s my code:

$usersday = (int)$_POST['day']; 
$usersyear = (int)$_POST['year']; 
$usersmonth = (int)$_POST['month'];
$takedate = date_create("$usersyear-$usersmonth-$usersday");
$date = date_format($takedate, 'd-m-Y');
$currentDate = date('Y-m-d'); 

2

Answers


  1. date_*() functions and date() are, confusingly, parts of two different Date library APIs. The the object-oriented version of date_*() functions clarifies it a bit, as well as being a more robust library. Eg:

    $usersyear = 2001;
    $usersmonth = 1;
    $usersday = 1;
    
    $takedate = new DateTime("$usersyear-$usersmonth-$usersday");
    $today    = new DateTime('today');
    $diff     = $today->diff($takedate);
    
    var_dump($diff, $diff->y);
    

    Output

    object(DateInterval)#3 (10) {
      ["y"]=>
      int(22)
      ["m"]=>
      int(7)
      ["d"]=>
      int(15)
      ["h"]=>
      int(0)
      ["i"]=>
      int(0)
      ["s"]=>
      int(0)
      ["f"]=>
      float(0)
      ["invert"]=>
      int(1)
      ["days"]=>
      int(8262)
      ["from_string"]=>
      bool(false)
    }
    int(22)
    

    Ref: https://www.php.net/manual/en/book.datetime.php

    Login or Signup to reply.
  2. I don’t about knowdeg php. But it will work to compare the data:

    <?php
    // Online PHP compiler to run PHP program online
    $pattern = "/(d{4})-(d{2})-(d{2})/";
    
    
    // user input date
    $usersday = 12; // (int)$_POST['day']; 
    $usersyear = 2021; // (int)$_POST['year']; 
    $usersmonth = 1; // (int)$_POST['month'];
    $takedate = date_create("$usersyear-$usersmonth-$usersday");
    $date = date_format($takedate, 'Y-m-d');
    // date to string format
    $userDateString = $takedate->format('Y-m-d');
    echo "n $userDateString";
    echo "n User Data: Year: $usersyear, Month: $usersmonth, Day: $usersday";
    
    // currrent date to string
    $cdate = new DateTime();
    $currentDateString = $cdate->format('Y-m-d');
    echo "n$currentDateString";
    
    if (preg_match($pattern, $currentDateString, $matches)) {
        $cyear = $matches[1];
        $cmonth = $matches[2];
        $cday = $matches[3];
    }
    
    echo "n Current Data: Year: $cyear, Month: $cmonth, Day: $cday";
    // Add your condition to compare data
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search