Galen
Galen

Reputation: 30170

Validating a date without knowing its format

I'm working on date validation for a validation library. A date format and a variable containing the date to validate will be supplied to the library.

$validator->validate( $_POST['date'], 'm/d/y' );

It's pretty easy to do basic validation with DateTime::createFromFormat()

if ( DateTime::createFromFormat( $format, $date ) !== false ) {
    // "valid" date
}

My issue is that with this method invalid dates such as 23/23/23 pass because the DateTime class will shift the date and set it to 2024-11-23. I know of the existence of checkdate() but without knowing the format I can't see a way to extract the origin month/day/year.

Any ideas on how to validate a date like this?

Upvotes: 2

Views: 452

Answers (1)

Baba
Baba

Reputation: 95131

Since you don't know the format of the date then you should use date_parse

date_parse — Returns associative array with detailed info about given date

Example

print_r(date_parse("23/23/23 00:14:38"));

Output

Array
(
    [year] => 2023
    [month] => 3            <------------------- Attempts to correct month 
    [day] => 23
    [hour] => 0
    [minute] => 14
    [second] => 38
    [fraction] => 0
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 1
    [errors] => Array
        (
            [0] => Unexpected character        <----- add errors found 
        )

    [is_localtime] => 
)

Simple Class

$date = "23/3/2013 00:14:38";
if (DateTimeParse::createFromString($date) !== false) {
    // "valid" date
}

Class Used

class DateTimeParse {

    public static function createFromString($string) {
        $date = date_parse(str_replace("/", "-", $string));
        if ($date['error_count'] > 0)
            return false;
        $date = sprintf("%d-%d-%d %d:%d:%d", $date['year'], $date['month'], $date['day'], $date['hour'], $date['minute'], $date['second']);
        return \DateTime::createFromFormat("Y-m-d g:i:s", $date);
    }
}

Upvotes: 3

Related Questions