When you do $ano/01/01
, you’re getting the value of $ano
and dividing by 1 twice (i.e., the result will be the very value of $ano
- in this case, 2019). This is because $ano
, although it is a string, is converted to integer by being in a numerical context.
But if you want dates referring to the first and last day of January of the current year, you can do so:
$d = new DateTime(); // data atual
$d->setDate($d->format('Y'), 1, 1); // mudar para 1 de janeiro deste ano
echo $d->format('Y-m-d'); // 2019-01-01
echo $d->format('Y-m-t'); // 2019-01-31
In the documentation you can see that the format t
shows the last day of the month (instead of the day contained in DateTime
).
Another alternative is to use strtotime
, that accepts some special formats to create specific dates. Then just use date
to print in the desired format:
echo date('Y-m-d', strtotime('first day of january this year')); // 2019-01-01
echo date('Y-m-d', strtotime('last day of january this year')); // 2019-01-31
Will iterate for several months (as per your comment), an alternative is to set the starting date and add up to one month. Ex:
$d = new DateTime(); // data atual
$d->setDate($d->format('Y'), 1, 1); // 1 de janeiro do ano atual
$umMes = new DateInterval('P1M');
for ($i = 0; $i < 12; $i++) { // iterar por 12 meses
echo $d->format('Y-m-d'). PHP_EOL;
echo $d->format('Y-m-t'). PHP_EOL;
$d->add($umMes); // ir para o próximo mês
}
To add one month I use one DateInterval
, that accepts a string in ISO 8601 format. In the case, P1M
corresponds to a duration of one month. The above code prints the first and last day of January to December 2019.
If you want, you can call setDate
by passing the specific values instead of adding up a month. Adapt the values according to what you need. If you want to go back a month, for example, just use sub
instead of add
.
You can also use a specific year value instead of using the current year:
$d->setDate(2018, 1, 1); // 1 de janeiro de 2018
Anyway, change the values according to what you need, because the basic logic is the same.
There’s a syntax error in your code.
– viana