2012-04-17 2 views
3

나는 과거의 타임 스탬프를 가지고있는 DateTime 객체를 가지고 있습니다.PHP : DateTime이 만료되지 않았는지 확인

이제이 DateTime이 예를 들어 48 시간보다 오래되었는지 확인하고 싶습니다.

어떻게하면 좋을까요?

감사

편집 : 안녕하세요, 도움을

감사합니다. 도우미 메서드를 사용합니다. 명명 구조가 있습니까?

protected function checkTemporalValidity(UserInterface $user, $hours) 
{ 
    $confirmationRequestedAt = $user->getConfirmationTokenRequestedAt(); 
    $confirmationExpiredAt = new \DateTime('-48hours'); 

    $timeDifference = $confirmationRequestedAt->diff($confirmationExpiredAt); 

    if ($timeDifference->hours > $hours) { 
     return false; 
    } 

    return true; 
} 
+1

'isExpired()'만료 된 경우? :) –

+0

감사합니다 :) 내가 var 이름으로 무엇을하는지 볼 수 있습니다 – bodokaiser

+0

그것은 약간 다른 '날짜()'포맷, [DateInterval :: format()] (http://www.php.net/ manual/ko/dateinterval.format.php). 그러나 'DateInterval'에는'hours '와 같은 멤버 변수가 없습니다. 문서를보십시오 :) –

답변

4
$a = new DateTime(); 
$b = new DateTime('-3days'); 

$diff = $a->diff($b); 

if ($diff->days >= 2) { 
    echo 'At least 2 days old'; 
} 

'테스트'목적으로 $ a와 $ b를 사용했습니다. DateTime::diffDateInterval object을 반환하며 실제 날짜 차이를 반환하는 멤버 변수 days을 반환합니다.

+0

더 나은 사용 (float) $ diff-> format ('% R % a'); $ diff-> days 대신 – bleuscyther

0

나는이 대답은 조금 늦게 알아,하지만 어쩌면 그것은 다른 사람 도움 :

/** 
* Checks if the elapsed time between $startDate and now, is bigger 
* than a given period. This is useful to check an expiry-date. 
* @param DateTime $startDate The moment the time measurement begins. 
* @param DateInterval $validFor The period, the action/token may be used. 
* @return bool Returns true if the action/token expired, otherwise false. 
*/ 
function isExpired(DateTime $startDate, DateInterval $validFor) 
{ 
    $now = new DateTime(); 

    $expiryDate = clone $startDate; 
    $expiryDate->add($validFor); 

    return $now > $expiryDate; 
} 

$startDate = new DateTime('2013-06-16 12:36:34'); 
$validFor = new DateInterval('P2D'); // valid for 2 days (48h) 
$isExpired = isExpired($startDate, $validFor); 

당신은 또한 전체 일 이외의 기간을 테스트 할 수 있습니다이 방법, 그것은 이전의 PHP 버전으로 Windows 서버에서 작동 너무 (DateInterval->days이 항상 6015를 반환하는 버그가있었습니다).

일 작업을하지 않으려는 사람들을 위해
0

...

당신은 DateTime::getTimestamp() 방법 유닉스 타임 스탬프를 얻을 수 있습니다. 유닉스 타임 스탬프는 초 단위로 처리하기 쉽습니다. 그래서 당신은 할 수 있습니다 :

$now = new DateTime(); 
$nowInSeconds = $now->getTimestamp(); 

$confirmationRequestedAtInSeconds = $confirmationRequestedAt->getTimestamp(); 

$expired = $now > $confirmationRequestedAtInSeconds + 48 * 60 * 60; 

$expiredtrue 될 것입니다 시간이

관련 문제