How to put variables in datetime (PHP)

Asked

Viewed 522 times

-3

Hello. I wonder if I can put variables in the values of datetime. Example:

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

If yes, how?

  • Yes, it’s possible, you’re having some difficulty doing this?

3 answers

2

The sign ' known as single quotes or apostrophe does not accept variables, as this in your example:

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

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

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

You can also concatenate:

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

Example of use, adding another day:

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

Documentation of the Datatime:

2


William’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 on IDEONE


More details on

http://php.net/manual/en/datetime.setdate.php

  • Prettier that way

  • @Wallacemaxters and freebies, avoids PHP doing the string parse. But the explanation of William is important for the OP understand the problem, so took my +1 too :)

  • @Beautiful wallacemaxters would be if the PHP constructor allowed to do this on a line, but not only does the language not allow to have more than one constructor signature, but avoids the use of the dynamicity of the language to have a method capable of making and decision according to the parameter. PHP has become a language that does not do well with static typing and is ruining the use of dynamic typing. I’m not going to say that some classes, this one among them, could have chosen a builder default, that absurdly can only be unique, better than the adopted, after all there are even reasons for this choice. Only khda.

  • @Mustache worse than having one, it’s guys picking some pretty shady ones to boot things up. Datetime is a class that almost always I take from the codes, to make it cleaner and more efficient. Almost always the functions date(), gmdate(), and those of time based on Unix time are better and more efficient.

  • @bigown as you said yourself, in PHP, the way to build the object in different ways is by using static methods. You see a problem with that (I think I saw you dispute that in a reply)?

  • Yeah, but where are the static methods of Datetime?

Show 1 more comment

0

To try to do it in a more simplified way than the two answers presented, if you are using a version equal to or greater than 5.4, you can do so

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

Browser other questions tagged

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