php dateTime :: createFromFormat在5.2? [英] php dateTime::createFromFormat in 5.2?

查看:122
本文介绍了php dateTime :: createFromFormat在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升级的机会)。

解决方案

只需包含下一个代码

 函数DEFINE_date_create_from_format()
{

函数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和%d对应于date()的Y m和d。
//%I对应于H,%M到i和%p到a
$ ugly = strptime($ schedule,$ schedule_format);
$ ymd = sprintf(
//这是一个格式字符串,需要六个总十进制
//参数,然后将它们的零填充到
// 4或2个字符,根据需要
'%04d-%02d-%02d%02d:%02d:%02d',
$ ugly ['tm_year'] + 1900,//这将是111 ,所以我们需要添加1900.
$ ugly ['tm_mon'] + 1,//这将是一个月减一个,所以我们添加一个
$ 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();


I have been developing on php 5.3.

However our production server is 5.2.6.

I have been using

$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;

However that function is not available in 5.2

What is the easiest way to get around this (no chance of a php upgrade).

解决方案

just include the next code

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

这篇关于php dateTime :: createFromFormat在5.2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆