【问题标题】:date_create_from_format equivalent for PHP 5.2 (or lower)相当于 PHP 5.2(或更低版本)的 date_create_from_format
【发布时间】:2011-02-06 23:08:36
【问题描述】:

我在本地机器上使用 PHP 5.3,需要解析英国日期格式 (dd/mm/yyyy)。我发现strtotime 不适用于那种日期格式,所以我改用date_create_from_format - 效果很好。

现在,我的问题是我的登台服务器运行的是 PHP 5.2,而 date_create_from_format 在该版本上不起作用。 (它是一个共享服务器,不知道如何将它升级到 PHP 5.3)

那么我可以使用与date_create_from_format 类似的功能吗?定制还是 PHP 原生?

【问题讨论】:

    标签: php date


    【解决方案1】:

    如果你只需要解析一种特定的格式,那就是基本的字符串操作。

    list($d,$m,$y)=explode("/",$datestr);
    

    【讨论】:

    • 这只会给他三个字符串,而不是解析的日期
    • @stereofrog 呃哦有什么问题:)
    【解决方案2】:

    试试strptime(),它在 PHP 5.1 及更高版本中可用。

    【讨论】:

    • 谢谢戴夫。是的,我在 Windows 上进行本地开发(使用 XAMPP,PHP 5.3),但登台和实时服务器是 LAMP,所以这可以作为后备。
    【解决方案3】:

    如果您无法使用strptime,那么这里有一个不同的想法。它类似于 Col. Shrapnel 的方法,但使用 sscanf 将日期部分的值解析为变量,并使用这些值构造一个新的 DateTime 对象。

    list($day, $month, $year) = sscanf('12/04/2010', '%02d/%02d/%04d');
    $datetime = new DateTime("$year-$month-$day");
    echo $datetime->format('r');
    

    【讨论】:

      【解决方案4】:

      包含此代码:

      function DEFINE_date_create_from_format()
      {
      
        function date_create_from_format( $dformat, $dvalue )
        {
      
          $schedule = $dvalue;
          $schedule_format = str_replace(array('Y','m','d', 'H', 'i','a'),array('%Y','%m','%d', '%I', '%M', '%p' ) ,$dformat);
          // %Y, %m and %d correspond to date()'s Y m and d.
          // %I corresponds to H, %M to i and %p to a
          $ugly = strptime($schedule, $schedule_format);
          $ymd = sprintf(
              // This is a format string that takes six total decimal
              // arguments, then left-pads them with zeros to either
              // 4 or 2 characters, as needed
              '%04d-%02d-%02d %02d:%02d:%02d',
              $ugly['tm_year'] + 1900,  // This will be "111", so we need to add 1900.
              $ugly['tm_mon'] + 1,      // This will be the month minus one, so we add one.
              $ugly['tm_mday'], 
              $ugly['tm_hour'], 
              $ugly['tm_min'], 
              $ugly['tm_sec']
          );
          $new_schedule = new DateTime($ymd);
      
         return $new_schedule;
      
        }
      }
      
      if( !function_exists("date_create_from_format") )
        DEFINE_date_create_from_format();
      

      【讨论】:

      • 感谢您的想法。不幸的是,即使在我添加了从 's' 到 '%S' 的映射之后,我也无法使用格式 'Y-m-d H:i:s' 来使用它......
      【解决方案5】:

      使用格式 DD-MM-YY 和时间戳,我想你会更容易

      $date="31-11-2015";
      $timestamp=strtotime($date);
      $dateConvert=date('d-m-Y', $timestamp);
      echo $dateConvert;
      

      我用过

      【讨论】:

        猜你喜欢
        • 2012-03-11
        • 2012-07-07
        • 2016-10-22
        • 1970-01-01
        • 1970-01-01
        • 2017-12-31
        • 2023-03-19
        • 1970-01-01
        • 2012-03-10
        相关资源
        最近更新 更多