I cannot compare dates with Datetime() in PHP

Asked

Viewed 77 times

0

I have a form where I send the date 1-4-2017 in each separate field(day, month and year). The code below receives the date normally, but when it arrives at the part of the comparison it does not occur, the result should be the display of an error message because the date that the form sends is less than the date that is in the variable $range_start, someone can help me?

<?php

    //cria um objeto datetime para seis meses atrás
    $range_start = new DateTime("6 months ago");

    //cria um objeto DateTime para hoje
    $range_end = new DateTime();

    //há um ano de quatro dígitos em $_POST['year']
    $input['day'] = filter_input(INPUT_POST, 'day', FILTER_VALIDATE_INT, array('options'=>array('min_range'=>1, 'max_range'=>31)));
    $input['month'] = filter_input(INPUT_POST, 'month', FILTER_VALIDATE_INT, array('options'=>array('min_range'=>1, 'max_range'=>12)));
    $input['year'] = filter_input(INPUT_POST, 'year', FILTER_VALIDATE_INT, array('options'=>array('min_range'=>1900, 'max_range'=>2100)));

    print $input['year'].'-'.$input['month'].'-'.$input['day'];

    if($input['year'] && $input['month'] && $input['day'] && checkdate($input['month'], $input['day'], $input['year'])){
        $submitted_date = new DateTime($input['year'].'-'.$input['month'].'-'.$input['day']);
       print "<br/>".$submitted_date->format("Y-m-d");
        if(($range_start> $submitted_date)||($range_end< $submitted_date)){
            $errors[] = 'Please choose a date less than six months old.';
        }
    }else{
        $errors[] = 'Please enter a valid date';
    }

    if($erros){
        foreach($errors as $msg){
            print $msg."\n".$input['day'];
        }
    }
?>
  • 1

    Possible duplicate of How to compare dates in PHP

  • Options on how to compare dates in the quoted question are not lacking.

  • if($erros) shouldn’t be if($errors) ? And if the idea is to know if there is the best is to use isset. In comparison ($range_end< $submitted_date) is also changed because $range_end must be bigger than $submitted_date.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.