PHP校验时间

一直用strtotime校验,总觉得不太准确:

<?php

/**
 * 校验时间格式必须为Ymd格式或者Y-m-d格式
 *
 * @param string $data 20200101|202-01-01
 * @return bool
 */
function checkSimpleDateFormat($date)
{
    //匹配日期格式
    $dateTime = date_create($date);
    if (!$dateTime || $date != date_format($dateTime, 'Ymd') || $date != date_format($dateTime, 'Y-m-d')) {
        return false;
    } else {
        if (!checkdate(date_format($dateTime, 'm'), date_format($dateTime, 'd'), date_format($dateTime, 'Y'))) {
            return false;
        }
    }
    return true;
}

比正则简单一些;

当然如果要校验必须为 2000年到2200年的时间格式,还是转时间戳比大小吧 ~

参考:

https://www.runoob.com/w3cnote/date-format-validation-in-php.html

I can see a bigger world.
原文地址:https://www.cnblogs.com/xuweiqiang/p/14577863.html