Friday, May 26, 2017

PHP strtotime() does not work with dd/mm/yyyy Format

Hello,

This is quick blog regarding PHP strototime function. In our recent project we were importing data from CSV where we faced two issues.

1) If we try to import date like 01/05/2016 considering dd/mm/yyyy format, it saves date in database as 2015-01-05

2) If we try to import date like 31/08/2016 considering dd/mm/yyyy format, it saves data in database as 1970-01-01

In short month and day is swiped while saving. So in case of date like 31/08/2016,  31 is assumed as month and there is no such month in calendar so it gave error and returns date like 1970-01-01

This is first time we faced such issue. I was not sure what's the exact issue but I assumed it has something to do with separator. So we tried same dates with  - instead of / and it worked. So to solve this temporary, we had following solution.

$date = '31/08/2016';
$date = str_replace('/', '-', $date);
echo date('Y-m-d', strtotime($date));

So we replace / with - and it worked but solving problem is not enough, we shall go in deep to check why we had this problem so curiously I looked into function documentation of strtotime and found out following.

"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; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. "

So indeed the problem here was with the separator.

Hope this helps you.

No comments:

Post a Comment