Subtract 1 month in PHP date

Asked

Viewed 1,135 times

2

How to reduce 1 month in a PHP date? I am trying to use this way but am getting an incorrect date

$dtini = '16/09/2019';

echo date('d/m/Y', strtotime('-1 month', strtotime($dtini)));

Result = 01/12/1969

What is wrong ?

  • 1

    dd/mm/yyyy is a valid format for the function strtotime?

  • 3

    Basically, strtotime interprets the format 16/09/2019 as "month/day/year", and as 16 is not a valid month, it returns FALSE, which is converted to zero, which date interprets it as January 1, 1970 (and subtracting 1 month results in December 1, 1969). It has a detailed explanation of this behavior here in this answer and solution options in that other

  • 1

    Format is not correct for function strtotime.

  • That’s right, thank you guys, it worked

  • Answers your question @Felipepacheco

1 answer

3


Surely this question should have duplicates, because working with dates is always a problem for those who don’t use them a lot, I sometimes curl up in something, but in the case of @Felipepacheco the solution is simple:

The reference date

$dtini = '16/09/2019';

The problem in subtraction

You find a problem for the function strtotime() as you put in the question, due to the fact of the variable $dtini be formatted in a different pattern, but that for us is the common standard, to solve it is simple:

The solution

Just replace the / for - using a native PHP function called str_replace() thus:

str_replace("/","-",$dtini);

Finally the subtraction will be as follows:

echo //imprime na tela
    date('d/m/Y',//converte para o formato desejado
        strtotime('-1 month',//subtrai a data
            strtotime(//Converte a data 
                str_replace("/","-",$dtini)//Substitui as barras
            )
        )
    );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.