Programing

PHP DateInterval에서 총 초 계산

lottogame 2020. 9. 2. 20:30
반응형

PHP DateInterval에서 총 초 계산


두 날짜 사이의 총 시간 (초)을 계산하는 가장 좋은 방법은 무엇입니까? 지금까지 다음과 같은 내용을 시도했습니다.

$delta   = $date->diff(new DateTime('now'));
$seconds = $delta->days * 60 * 60 * 24;

그러나 daysDateInterval 객체 속성은 현재 PHP5.3 빌드에서 손상된 것 같습니다 (적어도 Windows에서는 항상 동일한 6015값을 반환 함 ). 나는 또한 매월 일수 (반올림 30), 윤년 등을 보존하지 못하는 방식으로 시도했습니다.

$seconds = ($delta->s)
         + ($delta->i * 60)
         + ($delta->h * 60 * 60)
         + ($delta->d * 60 * 60 * 24)
         + ($delta->m * 60 * 60 * 24 * 30)
         + ($delta->y * 60 * 60 * 24 * 365);

그러나 나는이 반쪽짜리 솔루션을 사용하는 것에 정말로 만족하지 않습니다.


대신 타임 스탬프비교할 수 없습니까?

$now = new DateTime('now');
$diff = $date->getTimestamp() - $now->getTimestamp()

이 함수를 사용하면 DateInterval 객체에서 총 기간 (초)을 가져올 수 있습니다.

/**
 * @param DateInterval $dateInterval
 * @return int seconds
 */
function dateIntervalToSeconds($dateInterval)
{
    $reference = new DateTimeImmutable;
    $endTime = $reference->add($dateInterval);

    return $endTime->getTimestamp() - $reference->getTimestamp();
}

다음과 같이 할 수 있습니다.

$currentTime = time();
$timeInPast = strtotime("2009-01-01 00:00:00");

$differenceInSeconds = $currentTime - $timeInPast;

time ()은 epoch 시간 (1970-01-01T00 : 00 : 00) 이후 현재 시간을 초 단위로 반환하고 strtotime은 동일한 작업을 수행하지만 사용자가 제공 한 특정 날짜 / 시간을 기반으로합니다.


static function getIntervalUnits($interval, $unit)
{
    // Day
    $total = $interval->format('%a');
    if ($unit == TimeZoneCalc::Days)
        return $total;
    //hour
    $total = ($total * 24) + ($interval->h );
    if ($unit == TimeZoneCalc::Hours)
        return $total;
    //min
    $total = ($total * 60) + ($interval->i );
    if ($unit == TimeZoneCalc::Minutes)
        return $total;  
    //sec
    $total = ($total * 60) + ($interval->s );
    if ($unit == TimeZoneCalc::Seconds)
        return $total;  

    return false;
}

딱딱한 숫자 (60 * 60 대신-3600에 넣음)를 입력하면 매번 계산할 필요가 없습니다.

편집-귀하의 의견에 따라 번호를 수정했습니다.

참고 URL : https://stackoverflow.com/questions/3176609/calculate-total-seconds-in-php-dateinterval

반응형