Hello. I would like to know if I can put variables in the dateTime values. Example:
new Datetime('$ano-$mes-$dia');
If yes, how?
Hello. I would like to know if I can put variables in the dateTime values. Example:
new Datetime('$ano-$mes-$dia');
If yes, how?
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
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');
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 );