How to determine if value is a date in PHP

后端 未结 3 1394
不思量自难忘°
不思量自难忘° 2021-02-13 21:34

I am working with arrays of values in PHP. Some of these values may include a date in various string formats.

I need to convert dates in multiple formats to their numeri

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-13 22:02

    The problem with Pekka's script is that the date '2011-30-30' is also considered valid. This is the modified version.

    $formats = array("d.m.Y", "d/m/Y", "Ymd"); // and so on.....
    $dates = array(1,2,3,"4","11/12/2009","22/12/2000",true,false);
    
    foreach ($dates as $input) 
     { 
       foreach ($formats as $format)
        {
          echo "Applying format $format on date $input...
    "; $date = DateTime::createFromFormat($format, $input); if ($date == false || !(date_format($date,$format) == $input) ) echo "Failed
    "; else echo "Success
    "; } }

提交回复
热议问题