PHP determines whether the date format is valid

Source: Internet
Author: User

Implementation method

functionIsDate ($dateString ) {    return Strtotime(Date(' y-m-d ',Strtotime($dateString)) ) ===Strtotime($dateString );} Echo $this->isdate (' 2014-11-19 ')? ' True ': ' false ';Echo' </br> ';Echo $this->isdate (' 2014-11-32 ')? ' True ': ' false ';Echo' </br> ';Echo $this->isdate (' 2014-a-b ')? ' True ': ' false ';Echo' </br> ';Echo $this->isdate (' 2014-1-1 ')? ' True ': ' false ';Echo' </br> ';Echo $this->isdate (' 2014-01-01 ')? ' True ': ' false ';/*result Truefalsefalsetruetrue*/    

Date (' y-m-d ', Strtotime ($dateString)) This code converts the input time string to a Unix timestamp (since 1970-1-1 0:0:0) and then back to the date string. If the date string entered is not properly formatted, the value before the conversion is inconsistent with the converted value, that is, the date (' y-m-d ', Strtotime ($dateString)) = = = $dateString The result of this code will be false. Then why write the above code strtotime (date (' y-m-d ', Strtotime ($dateString))) = = = Strtotime ($dateString)? Because the code is written as date (' y-m-d ', Strtotime ($dateString)) = = $dateString So, if the value of $datestring is 2014-1-1 this format (a valid time string), The returned result will also be false, because date (' y-m-d ', strtotime (' 2014-1-1 ') returns the result as 2014-01-01, and if the month and date are single digit, it will be automatically 0 in the front, From the aspect of string comparison, 2014-1-1 is obviously not equal to 2014-01-01, so we need to add strtotime to the outer layer, convert the date on both sides to the Unix timestamp, and then compare.

Original address: http://chhblog.com/article/294.html

PHP determines whether the date format is valid

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.