문제

I need to add a month for the date format yyyymm. For eg. '201312' would result in '201401'. Here's what I have currently and it's not working correctly.

function addMonth($year_month){
$year_month = (int) $year_month;
if($year_month%100 == 1) {return $year_month-89;}
return $year_month+1;
}
도움이 되었습니까?

해결책

This is easier if you use DateTime()

function addMonth($year_month){
    $date = DateTime::createFromFormat('Ym', $year_month);
    $date->modify('+1 month');
    return $date->format('Ym');
}

Alternative using DateInterval()

function addMonth($year_month){
    $date = DateTime::createFromFormat('Ym', $year_month);
    $date->add(new DateInterval('P1M'));
    return $date->format('Ym');
}

다른 팁

If you want to stick to integers try:

function addMonth($year_month){
    $year_month = (int) $year_month;
    if($year_month%100 == 12)
        return $year_month+89;
    else
        return $year_month+1;
}

A date time solution like John Condes is probably better, however if you want to roll your own for experience's sake, something like that below will work.

Using div and modulos to ensure you are in the right frames will work better if you for some reason need to add 2 months, you won't end up with a 13th month.

<?
function addMonth($year_month, $add=1){
    $year_month = (int) $year_month + $add;

    $month = $year_month % 100;
    $year = (int)($year_month / 100 + $month / 12) ;

    $month = (int)($month % 12);
    return $year * 100 + $month;
}

print addMonth("200101"); echo "\n";
print addMonth("200101",14); echo "\n";
print addMonth("200112"); echo "\n";
?>

On Codepad this outputs:

200102
200203
200201

You can shorten it further if needed to this, but must less than this begins looking unreadable):

function addMonth($year_month, $add=1){
    $year_month = (int) $year_month + $add;
    $months = $year_month % 100;
    return (int)($year_month / 100 + $months / 12) * 100 + (int)($months % 12);
}

Much simpeler:

$month = 201712 ;
$nextMonth = date("Ym", strtotime($month . '01 + 1 month'));
echo $nextMonth ;

Result:

201801
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top