-1

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?

W.H.
  • 17
  • 6
  • according to php manual "m is a Numeric representation of a month, with leading zeros like 01 through 12" – Sfili_81 Sep 07 '18 at 15:20
  • @Sfili_81 Yes I know, but the calculation is removing the 0, which I don't want to happen! – W.H. Sep 07 '18 at 15:22
  • You're subtracting 1 from the month, which will convert the string to an int and drop it the leading 0. – aynber Sep 07 '18 at 15:23
  • 1
    You cannot "keep" a leading 0 while doing integer math. You need to convert the result back to a string and prepend a `"0"` character. – user229044 Sep 07 '18 at 15:24
  • 1
    You could try sprintf("%02d", $this_month); – Fergal Andrews Sep 07 '18 at 15:24
  • @aynber There is no casting-to-hex involved here. A leading 0 only matters when *parsing* an integer literal, not when casting strings to integers at runtime. – user229044 Sep 07 '18 at 15:25
  • @meagar I've removed that part of my comment after I tested it. – aynber Sep 07 '18 at 15:29
  • Thanks @meagar - Any ideas why Abderrahim's answer got a downvote? It seems to work fine? – W.H. Sep 07 '18 at 15:29
  • @W.H. I've no idea, the downvoter is welcome (but not required) to offer an explanation. – user229044 Sep 07 '18 at 15:30
  • @meagar - I get that, but it makes it confusing. So is it something that you would personally recommend using? Or is there a simpler way than that, or even the way I originally coded? – W.H. Sep 07 '18 at 15:33
  • a shorter Version would be: `$d = (new DateTime())->sub(new DateInterval("P1M"));` - then use that DateTime-Object to output your desired format: `echo $d->format("Ym");` – Jeff Sep 07 '18 at 16:09

1 Answers1

0

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;
    ?>