0

I have checked that the input date is a valid date, now need to check for backward date where date_start must be before date_end.

I have tried several other option to no avail, I really dont want to compare the substring of the input if possible.

The input are from html5 date using chrome with format dd/mm/yyyy

class MY_Form_validation extends CI_Form_validation {

    public $CI;

    public function date_format($date) {
        if (($timestamp = strtotime($date)) === false) {
            return false;
        }
    }

    //error message stored in caller module language folder
    public function backward_date($date_start, $date_end) {

        $date_1 = new DateTime($date_start);
    $date_2 =  new DateTime($date_end);

    if ($date_1 > $date_2 == true) {
        return false;
    }
    else {
        return true;
    }
    }

}
  • 2
    Possible duplicate of [Comparing two dates](https://stackoverflow.com/questions/3847736/comparing-two-dates) – BenRoob Jul 11 '17 at 08:46

3 Answers3

0

try this one

public function backward_date($date_start, $date_end) {
    $ts1 = strtotime($date_start);
    $ts2 = strtotime($date_end);
    $seconds_diff = $ts2 - $ts1;
    return ($seconds_diff>0) ? true : false;
}
Kundan Prasad
  • 556
  • 5
  • 10
0

The problem here is that DateTime is not able to parse the string from 'dd/mm/yyyy' to a valid DateTime Object.

Here is the received error :

PHP Warning: Uncaught Exception: DateTime::__construct(): Failed to parse time string (27/10/2017)

In order to fix this, you could use the createFromFormat() method from the DateTime model to parse your string with a specified format.

$date_1 = DateTime::createFromFormat('d/m/Y', $date_start);

So your method would be like :

public function backward_date($date_start, $date_end) 
{
    $date_1 = DateTime::createFromFormat('d/m/Y', $date_start);
    $date_2 = DateTime::createFromFormat('d/m/Y', $date_end);

    return $date_1 <= $date_2;
}

Hope it helps.

JazZ
  • 4,469
  • 2
  • 20
  • 40
0

Try to this ... Working for me.

 function date_calculate($start_date, $end_date) {

   $dStart = new DateTime($start_date);
   $dEnd = new DateTime($end_date);
   $days=0;

  if ($dStart < $dEnd) {
    $dDiff = $dStart->diff($dEnd);
    $dDiff->format('%R');
    $days = $dDiff->days;
    return $days;
   } else {        
    return $days;
   }
 }
Ankur Radadiya
  • 245
  • 3
  • 11