How to put variables in dateTime (PHP)

-3

Hello. I would like to know if I can put variables in the dateTime values. Example:

new Datetime('$ano-$mes-$dia');

If yes, how?

    
asked by anonymous 13.05.2016 / 01:17

3 answers

2

Guilherme's answer already explains the basics well, and to complement, I leave here a path that seems technically appropriate, since you have the variables separately:

   $date = new DateTime();
   $date->setDate( $ano, $mes, $dia );

See working at IDEONE


More details on

  

link

    
13.05.2016 / 02:18
2

The ' sign known as single quote or apostrophe does not accept variables like this in its example:

new Datetime('$ano-$mes-$dia'); 

Only "normal quotes" accept, so you can do this:

new Datetime("$ano-$mes-$dia");

You can also concatenate:

new Datetime( $ano . '-' . $mes . '-' . $dia );

Example usage, adding another day:

<?php
$date = new DateTime("$ano-$mes-$dia");
$date->modify('+1 day');
echo $date->format('Y-m-d');

DataTime Documentation:

13.05.2016 / 01:41
0

To try to make it simpler than the two answers, if you are using a version that is equal to or greater than 5.4, you can do so

$date = (new DateTime())->setDate( $ano, $mes, $dia );
    
13.05.2016 / 02:26