PHP date conversion to strtotime

2019-01-09 19:48发布

I have an array where each record has a 'date' field. The dates are in this format: '10/09/2015'. When I use strtotime on these dates, some of them come out as false. I thought there was a mistake in data structure so I created this simple array and a simple foreach loop, and they output false in some cases. What does it not like?

$dates = [];

$someData = [
    '21/05/2014',
    '22/05/2014',
    '09/06/2014',
    '04/07/2014',
];

foreach($someData as $date) {
    $dates[] = strtotime($date);
}

print_r($dates);die;

2条回答
Juvenile、少年°
2楼-- · 2019-01-09 19:57

Be aware of dates in the m/d/y or d-m-y formats; if the separator is a slash (/), then the American m/d/y is assumed. If the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. To avoid potential errors, you should YYYY-MM-DD dates or date_create_from_format() when possible.

查看更多
女痞
3楼-- · 2019-01-09 20:11

You need to understand over here the date format of your date. Here m/d/Y is considered to be the standard American Date format.

So when your date is like

'09/06/2014',//it should be considered as 06 september 2014
'04/07/2014',//it should be considered as 07 april 2014

And when your date is like as

'21/05/2014',
'22/05/2014',

Then the above date doesn't fits within the standards of American Date Format i.e. m/d/Y instead what you can do over here is replace / along with - which converts your date into European Date Format which is d-m-Y

查看更多
登录 后发表回答