dongshi4589 2013-03-18 07:06
浏览 76
已采纳

在不知道其格式的情况下验证日期

I'm working on date validation for a validation library. A date format and a variable containing the date to validate will be supplied to the library.

$validator->validate( $_POST['date'], 'm/d/y' );

It's pretty easy to do basic validation with DateTime::createFromFormat()

if ( DateTime::createFromFormat( $format, $date ) !== false ) {
    // "valid" date
}

My issue is that with this method invalid dates such as 23/23/23 pass because the DateTime class will shift the date and set it to 2024-11-23. I know of the existence of checkdate() but without knowing the format I can't see a way to extract the origin month/day/year.

Any ideas on how to validate a date like this?

  • 写回答

1条回答 默认 最新

  • dongliantong3229 2013-03-18 07:48
    关注

    Since you don't know the format of the date then you should use date_parse

    date_parse — Returns associative array with detailed info about given date

    Example

    print_r(date_parse("23/23/23 00:14:38"));
    

    Output

    Array
    (
        [year] => 2023
        [month] => 3            <------------------- Attempts to correct month 
        [day] => 23
        [hour] => 0
        [minute] => 14
        [second] => 38
        [fraction] => 0
        [warning_count] => 0
        [warnings] => Array
            (
            )
    
        [error_count] => 1
        [errors] => Array
            (
                [0] => Unexpected character        <----- add errors found 
            )
    
        [is_localtime] => 
    )
    

    Simple Class

    $date = "23/3/2013 00:14:38";
    if (DateTimeParse::createFromString($date) !== false) {
        // "valid" date
    }
    

    Class Used

    class DateTimeParse {
    
        public static function createFromString($string) {
            $date = date_parse(str_replace("/", "-", $string));
            if ($date['error_count'] > 0)
                return false;
            $date = sprintf("%d-%d-%d %d:%d:%d", $date['year'], $date['month'], $date['day'], $date['hour'], $date['minute'], $date['second']);
            return \DateTime::createFromFormat("Y-m-d g:i:s", $date);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗