Reputation: 5651
I am working on a small application which imports several CSV files from different sites. Each site have their own format for date. Some of the formats are below.
'2013-12-04 11:32:21 +0000'
'04/12/2014 +0000'
'04/12/2014 +0000 11:32:21'
'Fri Mar 14 18:19:26 +0000 2014'
I need to convert above formats into simple format like 'd-m'Y'
. The problem here is that the formats aren't known in advance and I can't go and change the code every time a new CSV files needs to be added to system.
Is there a way using which I can convert all these formats into simple format? I've tried below but it doesn't work and I can't find any other solution.
$date = DateTime::createFromFormat(strtotime('2013-12-04 11:32:21 +0000'), '2013-12-04 11:32:21 +0000');
print_r($date->format('d-m-Y')); //Doesn't work
Thanks in advance for your help.
Upvotes: 1
Views: 2243
Reputation: 13728
try
$date = new DateTime('2013-12-04 11:32:21 +0000');
echo $date->format('Y-m-d H:i:s'); //2013-12-04 11:32:21
Read manual :- http://www.php.net/manual/en/datetime.format.php
if you want all to convert create an array of values and pass in datetime your values
Upvotes: 2
Reputation: 76646
PHP understands a lot of date formats. It's not required to use DateTime::createFromFormat()
here. Simply pass your date string to the DateTime
construct and format it on the go:
Example:
$array = [
'2013-12-04 11:32:21 +0000',
'04/12/2014 +0000',
'04/12/2014 +0000 11:32:21',
'Fri Mar 14 18:19:26 +0000 2014',
];
foreach ($array as $datestr) {
$dt = new DateTime($datestr);
echo $dt->format('Y-m-d') . "\n";
}
Output:
2013-12-04
2014-04-12
2014-04-12
2014-03-14
Upvotes: 6