1

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!

2
  • A regex will not replace 8...PM with 20. Not a good idea. I'm sure there's a php date parser you can use. Commented May 11, 2010 at 14:34
  • 1
    If you strip out the "at" text, this appears to go through strtotime just fine. Commented May 11, 2010 at 14:47

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.