PHP - strtotime() and datetime strange behavior

Mihail-Cosmin Munteanu

I have a some dates formatted as string in this format: 18-04-17. I want to convert them to dates.

At first I used strtotime() to change it to date:

$timestamp = strtotime($row['reqEndDate']);
$newdate = date("d-m-Y", $timestamp);
echo $newdate;

This outputs: 17-04-2018. As you can see it mistakes the day with the year.

Next I tried to use datetime, as follows:

$newdate = datetime::createFromFormat("d-m-Y", $row['reqEndDate']);
echo $newdate->format('d-m-Y');

This outputs: 18-04-0017 .This method gets the day correctly, but instead of 2017 it prints 0017.

Is there any reason for this behavior? Maybe some settings in my php setup to look for?

Mjh

Uppercase Y will produce 4 digit year. Lowercase y produces a two-digit year. Your code with DateTime should be:

$date = DateTime::createFromFormat('d-m-y', $row['reqEndDate']);
echo $date->format('d-m-Y');

You can read about supported formats in PHP's manual page about date.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related