Check this out…
<?php
$dates = array(
'A' => '2011-04-27 08:00:00',
'B' => '12/11/2010 20:00:00',
'C' => '2011/11/20 20:00:00',
'D' => '20110217'
);
$parser = new CompositeDateParser;
$parser->add(new TypeADateParser);
$parser->add(new TypeDDateParser);
foreach($dates as $type => $date){
printf(
"(%s) %s \
",
$type,
date('r', $parser->parse($date))
);
}
/*
(A) Wed, 27 Apr 2011 00:00:00 +0100
(B) Thu, 01 Jan 1970 01:00:00 +0100
(C) Thu, 01 Jan 1970 01:00:00 +0100
(D) Thu, 17 Feb 2011 00:00:00 +0000
*/
?>
You essentially just create a new parser to handle each date format, how each object does this is up to you, but the parse method must return false on failure or a timestamp on success.
For example, to handle Type A we use…
class TypeADateParser implements IDateParse
{
public function parse($date){
preg_match('~^([0-9]{4})-([0-9]{2})-([0-9]{2})~', $date, $match);
if(4 !== count($match)){
return false;
}
return mktime(0, 0, 0, $match[2], $match[3], $match[1]);
}
}
… and for Type D…
class TypeDDateParser implements IDateParse
{
public function parse($date){
preg_match('~([0-9]{4})([0-9]{2})([0-9]{2})~', $date, $match);
if(4 !== count($match)){
return false;
}
return mktime(0, 0, 0, $match[2], $match[3], $match[1]);
}
}
<?php
interface IDateParse
{
public function parse($date);
}
class CompositeDateParser implements IDateParse
{
protected
$parsers = array();
public function add(IDateParse $parser){
array_push($this->parsers, $parser);
return $this;
}
public function parse($date){
foreach($this->parsers as $parser){
if(false !== ($time = $parser->parse($date))){
return $time;
}
}
return false;
}
}
?>
You don’t have to use Regular Expressions, use whatever you see fit and be a strict as possible for that particular format.
How cool is that!?
Why don’t you try and create TypeBDateParser & TypeCDateParser?
Just shout if you get stuck or have any questions. 