sourcecode

두 날짜 사이의 달 수를 계산하는 우아한 방법?

codebag 2023. 8. 26. 11:21
반응형

두 날짜 사이의 달 수를 계산하는 우아한 방법?

변수에 두 개의 날짜가 있다고 가정해보죠.

$date1 = "2009-09-01";
$date2 = "2010-05-01";

다음 사이의 개월 수를 계산해야 합니다.$date2그리고.$date1($date2 >= $date1. 즉, 저는 받아야 합니다.8.

날짜 함수를 사용하여 얻을 수 있는 방법이 있습니까, 아니면 문자열을 폭발시켜 필요한 계산을 해야 합니까?

감사해요.

PHP >= 5.3의 경우

$d1 = new DateTime("2009-09-01");
$d2 = new DateTime("2010-05-01");

var_dump($d1->diff($d2)->m); // int(4)
var_dump($d1->diff($d2)->m + ($d1->diff($d2)->y*12)); // int(8)

DateTime::diff가 DateInterval 개체를 반환합니다.

PHP 5.3 이상으로 실행하지 않으면 unix 타임스탬프를 사용해야 할 것 같습니다.

$d1 = "2009-09-01";
$d2 = "2010-05-01";

echo (int)abs((strtotime($d1) - strtotime($d2))/(60*60*24*30)); // 8

하지만 매우 정확하지는 않습니다(항상 한 달에 30일이 있는 것은 아닙니다)

마지막으로, 만약 그 날짜들이 당신의 데이터베이스에서 나온 것이라면, PHP가 아닌 DBMS를 사용하여 이 작업을 수행하십시오.

편집: DateTime::diff 또는 RDBMS를 사용할 수 없는 경우 이 코드는 더 정확해야 합니다.

$d1 = strtotime("2009-09-01");
$d2 = strtotime("2010-05-01");
$min_date = min($d1, $d2);
$max_date = max($d1, $d2);
$i = 0;

while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {
    $i++;
}
echo $i; // 8

또는 절차 스타일을 원하는 경우:

$date1 = new DateTime("2009-09-01");
$date2 = new DateTime("2010-05-01");
$interval = date_diff($date1, $date2);
echo $interval->m + ($interval->y * 12) . ' months';

업데이트: 몇 년 동안 설명할 코드 비트가 추가되었습니다.

또는 간단한 계산으로 다음을 얻을 수 있습니다.

$numberOfMonths = abs((date('Y', $endDate) - date('Y', $startDate))*12 + (date('m', $endDate) - date('m', $startDate)))+1;

정확하고 모든 경우에 효과적입니다.

이 방법은 두 날짜 사이의 월 수를 가져오는 또 다른 방법입니다.

// Set dates
$dateIni = '2014-07-01';
$dateFin = '2016-07-01';

// Get year and month of initial date (From)
$yearIni = date("Y", strtotime($dateIni));
$monthIni = date("m", strtotime($dateIni));

// Get year an month of finish date (To)
$yearFin = date("Y", strtotime($dateFin));
$monthFin = date("m", strtotime($dateFin));

// Checking if both dates are some year

if ($yearIni == $yearFin) {
   $numberOfMonths = ($monthFin-$monthIni) + 1;
} else {
   $numberOfMonths = ((($yearFin - $yearIni) * 12) - $monthIni) + 1 + $monthFin;
}

사용자:

$d1 = new DateTime("2009-09-01");
$d2 = new DateTime("2010-09-01");
$months = 0;

$d1->add(new \DateInterval('P1M'));
while ($d1 <= $d2){
    $months ++;
    $d1->add(new \DateInterval('P1M'));
}

print_r($months);

DateTime을 사용하면 몇 개월 동안 보다 정확한 솔루션을 얻을 수 있습니다.

$d1 = new DateTime("2011-05-14");
$d2 = new DateTime();
$d3 = $d1->diff($d2);
$d4 = ($d3->y*12)+$d3->m;
echo $d4;

당신은 여전히 남은 날들을 처리해야 할 것입니다.$d3->d만약 당신의 현실 세계의 문제가 두 날짜가 모두 달의 첫 번째 날인 원래 질문처럼 단순하고 간단하지 않다면 말입니다.

이것은 제가 우리 반에서 작성한 두 개의 주어진 날짜에 포함된 달의 수를 세기 위한 간단한 방법입니다.

public function nb_mois($date1, $date2)
{
    $begin = new DateTime( $date1 );
    $end = new DateTime( $date2 );
    $end = $end->modify( '+1 month' );

    $interval = DateInterval::createFromDateString('1 month');

    $period = new DatePeriod($begin, $interval, $end);
    $counter = 0;
    foreach($period as $dt) {
        $counter++;
    }

    return $counter;
}

날짜가 mySQL 쿼리의 결과 집합에 포함된 경우, 날짜 계산에 TIMESTAMPDIFF 함수를 훨씬 쉽게 사용할 수 있으며 반환 단위를 지정할 수 있습니다.Select TIMESTAMPDIFF(MONTH, start_date, end_date)months_diff from table_name

strtotime은 매우 정확하지 않고, 대략적인 카운트를 하며, 실제 날짜를 고려하지 않습니다.

날짜를 매월 항상 있는 날짜로 가져오는 것이 좋습니다.

$date1 = "2009-09-01";
$date2 = "2010-05-01";

$d1 = mktime(0, 0, 1, date('m', strtotime($date1)), 1, date('Y', strtotime($date1)));
$d2 = mktime(0, 0, 1, date('m', strtotime($date2)), 1, date('Y', strtotime($date2)));

 $total_month = 0;
 while (($d1 = strtotime("+1 MONTH", $d1)) <= $d2) {
     $total_month++;
 }
echo $total_month;

저는 이것을 사용했고 모든 조건에서 작동합니다.

$fiscal_year = mysql_fetch_row(mysql_query("SELECT begin,end,closed FROM fiscal_year WHERE id = '2'"));


            $date1 = $fiscal_year['begin'];
            $date2 = $fiscal_year['end'];

            $ts1 = strtotime($date1);
            $ts2 = strtotime($date2);


            $te=date('m',$ts2-$ts1);

            echo $te;

언급URL : https://stackoverflow.com/questions/4233605/elegant-way-to-get-the-count-of-months-between-two-dates

반응형