Question :
I have a form with a lease registration. In it, I have the fields $datainicio
, $meses
and $datatermino
. The start date I put automatic, according to the date of the day. The months should be placed at the time of registration, being 6, 12, 18, 24, 36, 48 or 60 months.
My problem is this: I would like to get the variable $datainicio
and add it with the variable $ months to get the value of $datatermino
, all at the time of registration.
I know that with pure PHP I can not do this. I have difficulties with jQuery. I would like your help.
$datainicio + $meses = $datatermino.
Answer :
You can do this with the add () method of the DateTime combining with the class DateInterval . What is done is adding a period determined by a string as P10D
(10 days);
$dataInicio = DateTime::createFromFormat('d/m/Y', '28/03/2016');
$dataInicio->add(new DateInterval('P10D'));
echo $dataInicio->format("d/m/Y"); //saida: 07/04/2016
//Obtem a data atual.
$date = date('Y-m-d'); //Data atual 29-03-2016
//Quantidade em meses para somar a data
$qtdMes = 6
//"quebra" a data em 3 partes usando como delimitador o "-"
list($year, $month, $day) = explode( '-', $date );
// Using the mktime function, we can add days, months, years, hours, minutes, and seconds
$date = mktime( 0 , 0 , 0 , $month + $qtdMeses, $day, $year );
//Mostra a data
echo date( 'd/m/Y', $date );
Another way to do this is:
$date = date('d-m-Y', strtotime( '+ 2 mounths' ) );
As a parameter in the strtotime function you can use days
, mounths
and years
.
I would use the Datetime
combined with the modify
method to change according to the months I want to add:
$mes_variavel = 3;
$datetime = new DateTime('2016-08-06');
$datetme->modify(sprintf('+%d months', $mes_variavel));
echo $datetime->format('d/m/Y');
You can use the strtotime()
function of PHP to perform several operations between dates including adding:
ini_set('date.timezone','America/Sao_Paulo');
$datainicio = '28-03-2016';
$meses = '2'; //adicionando meses
$datatermino= date('Y-m-d', strtotime("+".$meses." months", strtotime($datainicio)));
echo $datatermino;// SaĆda: 2016-05-28 , dois meses depois