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 ?
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 ?
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 php
You are not signed in. Login or sign up in order to post.
dd/mm/yyyy
is a valid format for the functionstrtotime
?– Woss
Basically,
strtotime
interprets the format16/09/2019
as "month/day/year", and as 16 is not a valid month, it returnsFALSE
, which is converted to zero, whichdate
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– hkotsubo
Format is not correct for function
strtotime
.– novic
That’s right, thank you guys, it worked
– Felipe Pacheco
Answers your question @Felipepacheco
– novic