Option 1: with MySQL
You can use date_sub
, writing the query like this:
$fecha_entrega="2017-09-05 00:00:00";
INSERT INTO entregas (fecha_entrega, fecha_preparar))
VALUES
($fecha_entrega, date_sub($fecha_entrega,INTERVAL 4 DAY));
CREATE TABLE IF NOT EXISTS restar_fecha (
id SERIAL NOT NULL PRIMARY KEY,
preparar DATETIME NOT NULL,
entregar DATETIME NOT NULL
);
INSERT INTO restar_fecha (entregar, preparar)
VALUES
('2017-09-05 00:00:00',date_sub('2017-09-05 00:00:00',INTERVAL 4 DAY)),
('2017-09-15 21:00:00',date_sub('2017-09-15 21:00:00',INTERVAL 4 DAY))
;
SELECT * FROM restar_fecha;
Resultado
:
id preparar entregar
1 01.09.2017 00:00:00 05.09.2017 00:00:00
2 11.09.2017 21:00:00 15.09.2017 21:00:00
Option 2: with PHP
You can use DateTime::sub
<?php
$fecha_e = new DateTime('2017-09-05 00:00:00');
$fecha_entrega=$fecha_e->format('Y-m-d H:i:s'). "\n";
$fecha_p=$fecha_e->sub(new DateInterval('P4D'));
$fecha_prepara=$fecha_p->format('Y-m-d H:i:s') ;
echo "Fecha entrega: ".$fecha_entrega. "\n";
echo "Fecha prepara: ".$fecha_prepara. "\n";
/* SQL Se recomienda mejor usar consultas preparadas*/
$sql = "INSERT INTO tabla (entrega, prepara)
VALUES ($fecha_entrega, $fecha_prepara);";
?>
Resultado:
Fecha entrega: 2017-09-05 00:00:00
Fecha prepara: 2017-09-01 00:00:00
We can also have a PHP function that allows more flexibility in the use of the code, in case we need to execute the operation in multiple parts of an application:
/**
* Sustraer intervalo a una fecha dada.
*
*
* @param datetime $fecha_inicial : fecha dada.
* @param string $intervalo : Intervalo de días a sustraer.
* @param string $formato : Formato de salida de la fecha/hora.
* @return array $fechas : Fechas resultantes.
*/
function sub_date ($fecha_inicial, $intervalo, $formato)
{
$fecha_i = new DateTime($fecha_inicial);
$fecha_inicial=$fecha_i->format($formato);
$fecha_s=$fecha_i->sub(new DateInterval($intervalo));
$fecha_sub=$fecha_s->format($formato) ;
$fechas=array("inicial"=>$fecha_inicial, "sub"=>$fecha_sub);
return $fechas;
}
The function would create an array similar to this:
Array
(
[inicial] => 2017-09-05 00:00:00
[sub] => 2017-09-01 00:00:00
)
Here is a test code for the function. We can pass in parameter not only the date, but also the interval that we want to subtract, and in what format we want the results:
/*Probando la función*/
$arrFechas=sub_date('2017-09-05 00:00:00','P4D','Y-m-d H:i:s');
print_r($arrFechas);
echo "Entrega: ".$arrFechas["inicial"]."\n";
echo "Prepara: ".$arrFechas["sub"]."\n";
--- Resultado
Entrega: 2017-09-05 00:00:00
Prepara: 2017-09-01 00:00:00
Note: To make the code more secure, it is convenient to use prepared queries.