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

前端 未结 16 2291
名媛妹妹
名媛妹妹 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条回答
  •  有刺的猬
    2020-11-22 18:02

    The easiest way to check if given date is valid probably converting it to unixtime using strtotime, formatting it to the given date's format, then comparing it:

    function isValidDate($date) { return date('Y-m-d', strtotime($date)) === $date; }

    Of course you can use regular expression to check for validness, but it will be limited to given format, every time you will have to edit it to satisfy another formats, and also it will be more than required. Built-in functions is the best way (in most cases) to achieve jobs.

提交回复
热议问题