Tengo una fecha en este formato:
2009-01-01
¿Cómo devuelvo la misma fecha pero 1 año antes?
Tengo una fecha en este formato:
2009-01-01
¿Cómo devuelvo la misma fecha pero 1 año antes?
Respuestas:
// set your date here
$mydate = "2009-01-01";
/* strtotime accepts two parameters.
The first parameter tells what it should compute.
The second parameter defines what source date it should use. */
$lastyear = strtotime("-1 year", strtotime($mydate));
// format and display the computed date
echo date("Y-m-d", $lastyear);
Aunque hay muchas respuestas aceptables en respuesta a esta pregunta, no veo ningún ejemplo del submétodo que usa el \Datetimeobjeto: https://www.php.net/manual/en/datetime.sub.php
Entonces, como referencia, también puede usar a \DateIntervalpara modificar un \Datetimeobjeto:
$date = new \DateTime('2009-01-01');
$date->sub(new \DateInterval('P1Y'));
echo $date->format('Y-m-d');
Que devuelve:
2008-01-01
Para obtener más información sobre \DateInterval, consulte la documentación: https://www.php.net/manual/en/class.dateinterval.php
Puede utilizar la siguiente función para restar 1 o cualquier año de una fecha.
function yearstodate($years) {
$now = date("Y-m-d");
$now = explode('-', $now);
$year = $now[0];
$month = $now[1];
$day = $now[2];
$converted_year = $year - $years;
echo $now = $converted_year."-".$month."-".$day;
}
$number_to_subtract = "1";
echo yearstodate($number_to_subtract);
Y mirando los ejemplos anteriores, también puede usar lo siguiente
$user_age_min = "-"."1";
echo date('Y-m-d', strtotime($user_age_min.'year'));