Correctly determine if date string is a valid date in that format

前端 未结 16 2440
名媛妹妹
名媛妹妹 2020-11-22 17:02

I\'m receiving a date string from an API, and it is formatted as yyyy-mm-dd.

I am currently using a regex to validate the string format, which works ok,

16条回答
  •  萌比男神i
    2020-11-22 18:01

    How about this one?

    We simply use a try-catch block.

    $dateTime = 'an invalid datetime';
    
    try {
        $dateTimeObject = new DateTime($dateTime);
    } catch (Exception $exc) {
        echo 'Do something with an invalid DateTime';
    }
    

    This approach is not limited to only one date/time format, and you don't need to define any function.

提交回复
热议问题