tags:

views:

102

answers:

1
+1  Q: 

PHP DateTime Regex

Hey, long story short I have inherited some terrible code. As a result a string comparison is buggy when comparing dates due to the format of the date. I am trying to convert the date to a valid DateFormat syntax so I can run a proper comparison.

These are some samples of the current format:

12/01/10 at 8:00PM

12/31/10 at 12:00PM

12/10/09 at 5:00AM

and so forth. I'd like to convert this to a YYYYMMDDHHMM format i.e 201012012000 for comparison purposes. If anyone can give me a quick regex snippet to do this that'd be appreciated as right now i'm hitting a brick wall for a regex. I can do it by exploding the string over several times etc but I'd rather do it in a more efficient manner.

Thanks!

+3  A: 

Working with dates in strange formats is very easy with the DateTime class which was built into PHP 5.3.

No need for regex or anything fancy:

$date = DateTime::createFromFormat('m/d/y \a\t g:iA', '12/10/09 at 5:00AM');
print_r($date);

Once it is a date object you can have it in any format you want.

evolve
Note that the `DateTime` class has been around since PHP 5.2.0, however `DateTime::createFromFormat` was indeed introduced with 5.3.0.
salathe