PHP uses the Strtotime and date functions to determine whether the date is valid code

Source: Internet
Author: User
Tags valid

 php Use the strtotime and date functions to check whether the date is valid code sharing, please refer to the use of the bar

First of all, it should be a simple function to judge whether the date is effective, but it's still a bit troublesome to think about it, because both the test format and the validity are checked. For example, 2013-02-29, although the format is correct, but the date is invalid, and 2012-02-29 format is correct, also valid.   A method can use the regular, but it is actually very difficult to understand, and the use of the regular in the test of effectiveness is not very good. A method is provided here, primarily by using the Strtotime and date functions for testing. Directly on the function:     Code as follows:/**  * Verify date format is correct  *   * @param string $date date  * @param string $forma TS need to verify format array  * @return Boolean  */function Checkdateisvalid ($date, $formats = Array ("y-m-d", "y/m/d")) {&nbsp ;   $unixTime = Strtotime ($date);     if (! $unixTime) {//strtotime conversion is not correct, the date format is clearly incorrect.         return false;    }      //validation date is valid, as long as one of the formats is met OK     foreach ($formats as $format) {        if (date ($format, $unixTime) = = $date) {            return true;   &NBSP ;    }    }       return false; The details of the       code comments are described in more detail and are no longer narrated. One thing to note: If you need a date format that is special, you cannot use this function if the Strtotime function cannot be resolved even in the correct format, but this should be veryIt's rare.   Some examples: The code is as follows: Var_dump (Checkdateisvalid ("2013-09-10")); Output True Var_dump (Checkdateisvalid ("2013-09-ha")); Output False Var_dump (Checkdateisvalid ("2012-02-29")); Output True Var_dump (Checkdateisvalid ("2013-02-29")); Output false  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.