在日期计算中保持领先0 [重复]

This question already has an answer here:

I want to get the last month/year based on this month/year, so I'm using the php code/calculation:

<?php
$this_month = date("m");
$this_year = date("Y");
if($this_month == "01"){
$history_month = "12";
$history_year = $this_year - 1;
}
else{
$history_month = $this_month - 1;
$history_year = $this_year;
}
$history_var = $history_year."".$history_month;
?>

Problem is, when I echo out history_var I see 20188 instead of 201808.

How do I keep the leading 0 on 08?

Alternatively, is there a simpler way to calculate last month?

</div>

Try this :

Test if $history_month less then 10 -> add Zero

 <?php
    $this_month = date("m");
    $this_year = date("Y");
    if($this_month == "01"){
    $history_month = "12";
    $history_year = $this_year - 1;
    }
    else{
    $history_month = $this_month - 1;
    $history_year = $this_year;
    }

    $history_month = $history_month >= 10 ? $history_month : "0".$history_month;

    $history_var = $history_year."".$history_month;
    ?>