PHP DateTime CreateFromFormat Issue

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


validateDate('09-2017', 'm-Y');
Function

was copied from this or php.net

I am very puzzled by why this returns false, as long as it returns true for previous months. Any ideas?

+4
source share
2 answers

This is because you do not deliver the day, so the current day is used by default. The current day is 31, but September has only 30 days, so it skips October 1.

Take a look at this example:

function validateDate($date, $format = 'm-Y') {
    $d = DateTime::createFromFormat($format, $date);
    echo $d->format("d-".$format); // added the day for debugging
    return $d && $d->format($format) == $date;
}
var_dump(validateDate('08-2017', 'm-Y')); // 31-08-2017, true
var_dump(validateDate('09-2017', 'm-Y')); // 01-10-2017, there no 31-09-2017, false
Function

was copied from this or php.net

This is a bit rudimentary, but you can determine if dthe format is there and manually set it to 1 to avoid this:

<?php
function validateDate($date, $format = 'm-Y') {
    if (strpos($format, "d") === false) {
        $format = "d ".$format;
        $date = "01 ".$date;
    }
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) === $date;
}
var_dump(validateDate('08-2017', 'm-Y')); // 31-08-2017, true
var_dump(validateDate('09-2017', 'm-Y')); // 01-09-2017, true
+5
source

. ; . : !, ( , , , , , , ) Unix Epoch; .

Fix:

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

php.net

+1

Source: https://habr.com/ru/post/1684840/


All Articles