Tuesday, April 19, 2011

php regex for passing date strings

Interesting thing is the strtotime function returns a value regardless of what the input is.

It doesn't throw an error. Not sure if this is by design.

I figure as I start doing useful things on my computer I'd share them (mostly for my doco benefit ;-)

EDIT: also, the reason for the regex hack in the tidy string is because the strtotime function didn't like 201104010800 as a time in php4, but was perfectly fine in php5.


=================== Code



function convertdate($datestring) {
   //convert 04/01/2011 08:00:59 -> 201104010800
   $date=date("YmdHi",strtotime("$datestring")) or exit("Date Conversion failed");
   return($date);
}

function convertdatetidy($datestring) {
   //convert 20110401080059 -> 04/01/2011 08:00:59
   $newdate=preg_replace('/(....)(..)(..)(..)(..)(..)/', '\2/\3/\1 \4:\5:\6', $datestring);
   $date=date("m/d/Y H:i",strtotime("$newdate")) or exit("Date Conversion failed");
   return($date);
}

No comments:

Post a Comment