5.2 中的 php dateTime::createFromFormat?

标签 php datetime php-5.2

我一直在使用 php 5.3 进行开发。

但是我们的生产服务器是 5.2.6。

我一直在用

$schedule = '31/03/2011 01:22 pm'; // example input
if (empty($schedule))
    $schedule = date('Y-m-d H:i:s');
else {
    $schedule = dateTime::createFromFormat('d/m/Y h:i a', $schedule);
    $schedule = $schedule->format('Y-m-d H:i:s');
}
echo $schedule;

但是该功能在 5.2 中不可用

解决这个问题的最简单方法是什么(没有机会升级 php)。

最佳答案

只包含下一段代码

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();

关于5.2 中的 php dateTime::createFromFormat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5399075/

相关文章:

PHP 从字符串中获取图像的所有 URL

php include html 添加空格

php - 如何减少 PHP 代码?

python - 使用日期时间对象

laravel - Laravel 5 中未定义的函数 link_to

javascript - 拍卖类型倒计时

Python xlrd 读取 DateTime 为序列号

java - 错误: validation failed for objects with date

php - 在 PHP 5.2 中模仿 PHP 5.3 DateTime

java - 从 PHP 5.2 运行 Java 的推荐方式是什么?