Add variables to obtain end date

Asked

Viewed 912 times

4

I have a form with a rental register. 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 must 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 take the variable $datainicio and add with the variable $months to get the value of $datatermino, all this at the time of registration.

I know that with pure PHP I can’t do it. I have difficulties with jQuery. I would like your help.

$datainicio + $meses = $datatermino.

  • Yes it is possible with pure PHP, believe me!

  • Really? If you have any references... I figured it wasn’t possible...

4 answers

1

You can do this with the method add() class Datetime combining with the class Dateinterval. What is done is adding a period determined by a string like 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

0

I would use the Datetime combined with the method modify 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');

0

You can use the function strtotime() 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

0

//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 sum up 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 parameter in strtotime function you can use days, mounths and years.

Browser other questions tagged

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