Change from day to month when adding minutes: Why does it occur? How to fix it?

Asked

Viewed 38 times

1

I wonder why in the code below, after adding the 15 minutes, there is a change in the order of day and month. What’s the logic behind it, if that’s what I’m thinking. Plus, how to fix this in PHP Procedural (neat), without using tricks like separating items and putting them back together.

date_default_timezone_set('America/Sao_Paulo');
$inicio = date('d/m/Y H:i:s', time());
echo $inicio . '<br>';

//Define horário de expiração
$adicionaMinutos = strtotime("$inicio +15 minute");
$expiracao = date('d/m/Y H:i:s', $adicionaMinutos);
echo $expiracao . '<br>';
  • Use $expiration = date('Y-m-d H:i:s'... and not $expiration = date(’d/m/Y H:i:s'.. https://www.php.net/manual/en/function.strtotime.php. The manual says : - "The function expects to be informed a string containing a date format in English US"

1 answer

2

The function date, despite the name, returns a string (which in turn represents a date in a given format).

Then the $inicio is a string in the "day/month/year" format, which in turn is passed to strtotime. And according to the documentation of strtotime, when there are three numbers separated by bar, it interprets as "month/day/year":

Dates in the m/d/y or d-m-y formats are disambiguated by Looking at the separator between the Various Components: if the separator is a Slash (/), then the American m/d/y is assumed

One solution is not to pass the string to strtotime, and yes the value that corresponds to the date (in this case, the return of time):

date_default_timezone_set('America/Sao_Paulo');
$now = time();

$inicio = date('d/m/Y H:i:s', $now);
echo $inicio . '<br>';

//Define horário de expiração
$adicionaMinutos = strtotime("@$now +15 minute");
$expiracao = date('d/m/Y H:i:s', $adicionaMinutos);
echo $expiracao . '<br>';

One detail is that, like time() returns the numeric value of timestamp, then it is necessary to use the @ before it (otherwise the number will be converted to string and interpreted as day, month, year, etc).


But of course, since we’re dealing with numbers, you can simply add up the amount of seconds equivalent to 15 minutes (because time() returns the timestamp in seconds):

date_default_timezone_set('America/Sao_Paulo');
$now = time();

$inicio = date('d/m/Y H:i:s', $now);
echo $inicio . '<br>';

//Define horário de expiração
$expiracao = date('d/m/Y H:i:s', $now + (15 * 60)); // somando 15 minutos
echo $expiracao . '<br>';
  • Very useful, of this detail I did not know the @ before the time()

  • @gleisin-dev PHP and its bizarrities: https://ideone.com/lNnFWL

  • 2

    Hahaha, a mere "drunk" processing things.. You will understand!

Browser other questions tagged

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