2017-09-19 1 views
1

두 날짜의 차이점을 찾고 싶습니다. 같은 날짜에 date_diff을 사용했습니다. date_diff 개체에 형식 기능을 적용하면 오류가 반환됩니다. boolean에 멤버 함수 format()을 호출하십시오.

부울

$field_value의 멤버 함수 형식()에

호출은 데이터베이스로부터 페치이며 형식 dd/mm/YYYY가요. $field_value$indexing_value의 값을 하드 코드하면 다음 코드가 작동합니다.

모든 것은 내가

$diff->format("%R%a") 

의 값을 출력 시도 행 번호 8까지 잘 실행되고 있으며 정확한 값을 반환하지만 코드는 if 문 근처에 오류가 있습니다.

$date = new DateTime(); 
$current_date = $date->format('d/m/Y'); 
$indexing_value = str_replace("/", "-", $field_value); 
$current_value = str_replace("/", "-", $current_date); 
$indexing_value = date_create($indexing_value); 
$current_value = date_create($current_value); 

$diff = date_diff($indexing_value, $current_value); 
if ($diff->format("%R%a") < 0) { 
    echo "1"; 
} else { 
    echo "2"; 
} 

위의 코드가 잘못되었음을 알려주십시오.

답변

1

diff가 있는지 여부를 확인하기위한 조건을 추가합니다. 오류가 있으면 false를 반환하므로 diff가 있는지 확인하십시오. 일부 값은 diff 날 위의 코드에 어떤 문제가 있는지 알려 주시기 바랍니다 $diff

0

가치 False을 계산하지 않기 때문에 당신은 오류가 발생하는 동일한

$diff = date_diff($indexing_value, $current_value); 
if ($diff) { 
    if ($diff->format("%R%a") < 0) { 
     echo "1"; 
    }else{ 
     echo "2"; 
    } 
} 

에 대한 manual을 확인합니다.

코드와 몇 가지 문제가 있습니다

  1. 당신은 date_create()에 의해 반환 된 값을 확인하지 않는다; FALSE on error을 반환합니다.

  2. 서식의 결과는 $date이며 결과 문자열에서 $current_value을 다시 생성합니까? 시간 구성 요소에 신경 쓰지 않고 DateTime 개체의 날짜 부분 만 사용해야하는 경우 setTime() 메서드를 사용하여 시간 구성 요소를 0으로 설정할 수 있습니다.

  3. str_replace() 형식을 알고있는 날짜의 텍스트 표현을 조작하려면 어떻게해야합니까? DateTime::createFromFormat()은 문자열을 DateTime 개체로 구문 분석하는 데 사용할 수 있습니다.

  4. 두 날짜의 차이와 형식을 계산할 필요가 없으며 값을 0과 비교할 필요가 없습니다. DateTime 개체를 직접 비교할 수 있습니다.

모두 모두, 당신이 필요로하는 모든 코드는 다음과 같습니다

// Current date & time 
$today = new DateTime(); 
// Ignore the time (change $today to "today at midnight") 
$today->setTime(0, 0, 0); 

// Parse the value retrieved from the database 
$field = DateTime::createFromFormat('d/m/Y', $field_value); 
// We don't care about the time components of $field either (because the time 
// is not provided in the input string it is created using the current time) 
$field->setTime(0, 0, 0); 

// Directly compare the DateTime objects to see which date is before the other 
if ($field < $today) { 
    echo "1"; 
} else { 
    echo "2"; 
} 
관련 문제