0

I have custom date format that looks like:

M jS Y g:i a (Feb 23rd 2016 3:32 pm )

It's really hard to write regex to that format like this, how I can detect that date have that format ?

2 Answers 2

3

If you don't need necessarily a regex, just use the date_create_from_format function. It returns FALSE if it's unable to parse the string, so you can check on its return value.

$dateObject = date_create_from_format("M jS Y g:i a", "Feb 23rd 2016 3:32 pm");
if ($dateObject === false) {
    // string is in a wrong format
}
Sign up to request clarification or add additional context in comments.

Comments

1

The regular expressions are not the best solution in your case. PHP already provides good support for date/time parsing from strings.

Use DateTime::createFromFormat() to parse your string. It returns a valid DateTime object when the parsing succeeds or FALSE when the parsing fails:

$date = DateTime::createFromFormat(
    'M jS Y g:i a',
    'Feb 23rd 2016 3:32 pm',
    new DateTimeZone('UTC')        // put your timezone here
);
print_r($date);

It displays:

DateTime Object
(
    [date] => 2016-02-23 15:32:00.000000
    [timezone_type] => 3
    [timezone] => UTC
)

Comments

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.