date does not show full date, only year

Asked

Viewed 66 times

-2

I have this situation that I need to take the current year and play in the variable janI and janF, on screen I send a echo and displays the date. However, it is only displaying 2019. The /01/01 is not appearing. What can be?

$ano=date('Y');
echo $ano;
$janI = $ano/01/01;
$janF = date('Y/01/31');
  • There’s a syntax error in your code.

1 answer

1


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.

  • in reality I want to take the first and last day of every month, but then I will pass in some way for example 2018 and then I needed something to keep the pattern

  • @Muriloalbeest I put a basic example, but if it’s not what you want, I suggest you edit your question detailing exactly what you need.

  • I ended up using the last option, but it worked. thanks to all

Browser other questions tagged

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