-4

I would like to calculate the difference between two php dates. But I get the following error:

Notice: Undefined variable: difference in C:\wamp\www\HR version 1.3\Applicant_Workdetails.php on line 68

I would also like to know if its best practice to calculate the difference this way.

if (isset($_GET['success']) && empty($_GET['sucess'])) {
    echo 'Submitted Successfully' . ' ';
    printf("%d years, %d months, %d days\n", $difference->y, $difference->m, $difference->d);  //This is line 68
} else {
    if (empty($_POST) === false && empty($errors) === true) {

        $startdate = $_POST['StartDate'];
        $enddate = $_POST['EndDate'];
        $datetime1 = new DateTime($startdate);
        $datetime2 = new DateTime($enddate);
        $difference = $datetime1->diff($datetime2);

        //Submit Workdetails to the database
        $personal_workdetails = array(
            'IndustryName' => $_POST['IndustryName'],
            'Occupation' => $_POST['Occupation'],
            'Position' => $_POST['Position'],
            'Job_description' => $_POST['Job_description'],
            'StartDate' => $startdate,
            'EndDate' => $enddate,
            'Personid' => $Personid,
            'Jobid' => $jobid);
        personal_workdetails($personal_workdetails);
        //redirect
        header('Location: Applicant_workdetails.php?success');
        exit();
    } else if (empty($errors) === false) {
        //output errors if the errors array is not empty
        echo output($errors);
    }
}
sectus
  • 15,605
  • 5
  • 55
  • 97
user1783675
  • 346
  • 2
  • 7
  • 25
  • 1
    So where (before that line) are you actually defining $difference? – Mark Baker Apr 04 '13 at 11:07
  • http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php?rq=1 – AKS Apr 04 '13 at 11:07
  • [Try to search](https://www.google.ru/search?q=difference+between+two+dates+php+site%3Astackoverflow.com) – sectus Apr 04 '13 at 11:08

3 Answers3

1

I don't see where $difference is created, could you please post the whole file so I can see where the problem is?

You do a printf() of $difference, but that variable is only declared (as far as I can see) some lines after.

Razican
  • 697
  • 2
  • 10
  • 16
1

On line 68 in "C:\wamp\www\HR version 1.3\Applicant_Workdetails.php" you are using a variable which you did not define. Possibly adding or subtracting or something. It's hard for us to find because we don't know what section of code you posted.

But just follow the instruction. PHP has made it clear where the error is.

Touch
  • 1,481
  • 10
  • 19
1

You can use DateTime::diff

  $datetime1 = new DateTime("$start_date");
  $datetime2 = new DateTime("$end_date");
    $interval = $datetime1->diff($datetime2);
    echo "Result " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
Tony Stark
  • 8,064
  • 8
  • 44
  • 63