PHP Subtract one month from date

I am creating a PDF sales report and I need my PDF to show the report from the previous month.

I am already using this:

<?php

date("F Y", strtotime("-1 months"));

?>

and it produces the result I need:

June 2020

However, since some months have 31 days, I’ve heard this code will not work since strtotime(); does not work for months with 31 days.

Is there an alternative way to code this properly or am I misunderstanding something?

strtotime("first day of last month")

or alternatively:
mktime(0,0,0,date('n')-1,1,date('Y'))

bit less readable, but mathematically sound.

What’s the difference in the two?

strtotime("-1 months") vs strtotime("first day of last month)

So which is better? Is there a preference or do they do the same thing?

strtotime suffers from how it does its calculations:
“-1 months” on 07/31/2020 makes the date 06/31/2020, which doesn’t exist, 06/31/2020 = 07/01/2020.

the mktime line says:
Create a date object with the hour set to 0, minute set to 0, the second set to 0, the month set to the current month number -1, the day set to 1, and the year set to the current year.

PHP will wrap correctly - and say that 00/01/2020 = 12/01/2019. We don’t rely on the day number from the current date - every month has a 1st.

So, if I’m understanding you correctly, I should use this

<?php date("F Y", mktime(0,0,0,date('n')-1,1,date('Y')) ?>

instead of this:

<?php date("F Y, strtotime("first day of last month)) ?>

I’m not… 100% on how strtotime handles “first day of last month”…specifically, its order of operations.

I THINK what it does is set the day to 1, and THEN subtract a month, which will work. (7/31/2020 -> 7/1/2020 -> 6/1/2020)

If it does it the OTHER way around, it wont work. (7/31/2020 -> 6/31/2020, which is actually 7/1/2020, and then setting the day to 1 results in 7/1/2020.)

mktime will always work, because you are hard-coding the value of the day.

I’m adding a commented line to my code, should strtotime not work, I’ll have an alternative.

I’m getting a lot of errors when I run this:

mktime(0,0,0,date('n')-1,1,date('Y'))

Warning : date() expects at most 2 parameters, 5 given in on line 14

might want to check the parenthesis if you’ve copied and pasted the line… specifically, i’m going to guess you’ve got an extra ) after date('n').

Looks correct to me… Here is the full line of code:

$this->Cell(265, 10, 'Sales Report | ' . date("F Y", mktime(0,0,0,date('n')-1,1,date('Y')), 0, 0, 'C'));

check again, the second-to-last ) in your line is in the wrong place…

Got it:

$this->Cell(265, 10, 'Sales Report | ' . date("F Y", mktime(0,0,0,date('n')-1,1,date('Y'))), 0, 0, 'C');

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.