Return date reversed in PHP

Asked

Viewed 181 times

5

I am preparing a report based on the initial date (start_date) and final date (end_date).

My return from filter comes through the POST, if I use then print_r($_POST), I note that the date comes in the Brazilian standard, normal.

$start_date = ($filter['start_date']) ? date("Y-m-d", strtotime($filter['start_date'])) : null;
$end_date = ($filter['end_date']) ? date("Y-m-d", strtotime($filter['end_date'])) : null;

When using strtotime() to reverse the date, only the start_date works.

`start_date` : 2019-01-12
`end_date` : 1970-01-01

Result the print_r($_POST);

Array
(
    [start_date] => 12/01/2019
    [end_date] => 26/01/2019
)

Note: I noticed that if I type 13/01/2019, the return will be 1970-01-01. So this happens because of the inversion, what would be the right way to do this?

1 answer

6


According to the documentation of strtotime, when the string passed is using / as separator, it is assumed that it is in format m/d/y (month/day/year).

In the case of start_date, the value is 12/01/2019, and so is interpreted as "December 1, 2019" (not January 12). So much so that by testing your code with this string, I got "2019-12-01" (I don’t know how you got it 2019-01-12, but finally).

Already in the case of end_date, the value is 26/01/2019, and strtotime will interpret as "day 1 of month 26", which results in an invalid date. In this case, strtotime returns FALSE.

The problem is that, when passing the FALSE for the function date, this value is interpreted as the number zero (since date expecting a int as a parameter).

And as this parameter is the value of timestamp (i.e., the number of seconds since 01/01/1970), the timestamp with zero value ends up resulting in 1970-01-01.


One way to settle is to trade strtotime for DateTime::createFromFormat, specifying what format the string is in (in this case, d/m/Y). This method returns a DateTime, which in turn has the method format, which can be used to get a string containing the date in another format (replacing date()):

// parsing da string, criando uma data
$date = DateTime::createFromFormat("d/m/Y", "26/01/2019");
// formatar a data (converter para outro formato)
echo ($date->format("Y-m-d")); // 2019-01-26

See this code working on Ideone.com.

Browser other questions tagged

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