dongshi3605 2010-11-19 14:48
浏览 39
已采纳

如何确定值是否是PHP中的日期

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 numerical equivalent (Unix timestamp). The problem is being able to determine if the string is a date.

Using

if (($timestamp = strtotime($str)) === false)

will check for a valid date from a string but how do I determine if the value should even be validated as a date?

Example:

$x = {1,2,3,"4","11/12/2009","22/12/2000",true,false};

foreach($x as $value)
{

if(is_bool($value))

if(is_string($value))

if(is_numeric($value))

if(is_date($value)) ?

...

}

In short, is there an easy way to check if a string value is a date?

  • 写回答

3条回答 默认 最新

  • dougaoshang0237 2010-11-19 14:51
    关注

    In short, is there an easy way to check if a string value is a date?

    Not really, seeing as it could be in an arbitrary format.

    If at all possible, I would tend to leave parsing to the magic of strtotime(). If it manages to create a valid date, fine. If it doesn't, you'll receive false.

    Be prepared for the possibility of false positives, though, because strtotime() parses even things like "Last Friday".

    If strtotime() is too liberal for you, you could consider building a collection of date formats you want to accept, and run PHP 5.3's DateTime:createFromFormat using every one of the formats on every date.

    Something like (untested)

    $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...<br>";
    
          $date = DateTime::createFromFormat($format, $input);
          if ($date == false) 
           echo "Failed<br>";
          else
           echo "Success<br>";
        }
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路