2013-04-04 147 views
-4

我想计算两个php日期之间的差异。但我得到以下错误:计算两个日期之间的差异php

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

我也想知道如果它的最佳实践来计算差异这种方式。

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); 
    } 
} 
+1

那么,(在该行之前),你实际定义$区别? – 2013-04-04 11:07:56

+0

http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php?rq=1 – 2013-04-04 11:07:59

+0

[尝试搜索](https://www.google .ru/search?q =差异+ +两个+日期+ php +网站之间的差异%012stackoverflow.com) – sectus 2013-04-04 11:08:04

回答

1

我看不出其中创建$差别,你可以请张贴整个文件,这样我就可以看到问题出在哪里?

你做了$差异的printf(),但是这个变量只是声明了(据我所知)之后的一些行。

1

在“C:\ wamp \ www \ HR版本1.3 \ Applicant_Workdetails.php”中的第68行,您正在使用您未定义的变量。可能增加或减少什么。我们很难找到,因为我们不知道您发布了哪部分代码。

但只是按照指示。 PHP已经明确了错误在哪里。

1

您可以使用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 "; 
+0

阅读问题,不仅仅是标题。 – itachi 2013-04-04 11:13:59