2

Is there a possibility to check if DateTime() can parse a string? When I try for example:

new DateTime('05.06.17');

DateTime cant parse it and will throw a Exception. So, how can I prevent this and check before if the parsing is possible? There is a lot of possible formats DateTime can read and I don't want to check each of them with regex...

Asara
  • 2,791
  • 3
  • 26
  • 55

2 Answers2

0

Use date_parse which will take a date string and return an array containing details of the date. If it can't be parsed then it will return false so you can use:

if (date_parse($myDateSring) !== false) {
    //valid date
}

If $myDateSring is a valid date the function will return an indexed array of the date parts. For example:

print_r(date_parse("2006-12-12 10:00:00.5"));

Array
    (
        [year] => 2006
        [month] => 12
        [day] => 12
        [hour] => 10
        [minute] => 0
        [second] => 0
        [fraction] => 0.5
        [warning_count] => 0
        [warnings] => Array()
        [error_count] => 0
        [errors] => Array()
        [is_localtime] => 
    )
Andy
  • 698
  • 12
  • 22
  • unfortunately it does not work: `var_dump(date_parse('16/03/2017 17:13'))` gives true but `new DateTime('16/03/2017 17:13')` does not work – Asara Mar 16 '17 at 21:15
  • In that case you may need to inspect the resulting array and extract the parts you are interested in. I will update my answer with the example from the docs – Andy Mar 17 '17 at 13:42
0

The best option in this case is to make function which check if date is correct taking into account format.

If date can be created the it can be parse.

function validateDate($date, $format) {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

function was copied from this answer or php.net

Function return true or false.

Glavić
  • 42,781
  • 13
  • 77
  • 107
bobomam
  • 58
  • 7