5.2中的php dateTime::createFromFormat?

5.2中的php dateTime::createFromFormat?,php,datetime,php-5.2,Php,Datetime,Php 5.2,我一直在开发PHP5.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 = $schedul

我一直在开发PHP5.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升级的机会)。

因为当遇到D/M/Y时,它做得很差,
date\u create\u from\u format
不可用,这可能是您唯一的希望。它做了一些非常古老的事情,比如把年份当作1900年以来的年份来处理,把月份当作一月是零月份来处理。下面是一些可怕的示例代码,用于将日期重新组合为DateTime理解的内容:

$schedule = '31/03/2011 01:22 pm';
// %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, '%d/%m/%Y %I:%M %p');
$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']
);
echo $ymd;
$new_schedule = new DateTime($ymd);
echo $new_schedule->format('Y-m-d H:i:s');

如果它有效,您应该看到相同的、正确的日期和时间打印两次。

只需包含下一个代码即可

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

我认为扩展DateTime类并自己实现
createFromFormat()
会更简洁:-

class MyDateTime extends DateTime
{
    public static function createFromFormat($format, $time, $timezone = null)
    {
        if(!$timezone) $timezone = new DateTimeZone(date_default_timezone_get());
        $version = explode('.', phpversion());
        if(((int)$version[0] >= 5 && (int)$version[1] >= 2 && (int)$version[2] > 17)){
            return parent::createFromFormat($format, $time, $timezone);
        }
        return new DateTime(date($format, strtotime($time)), $timezone);
    }
}

$dateTime = MyDateTime::createFromFormat('Y-m-d', '2013-6-13');
var_dump($dateTime);
var_dump($dateTime->format('Y-m-d'));
这将适用于PHP>=5.2.0的所有版本

请看这里的演示

我在5.2版本的生产服务器上遇到了类似的问题,因此我使用上面的datetime创建了一个对象,然后按照我的喜好更改格式,如上所述。

仅限日期和时间

$dateTime = DateTime::createFromFormat('Y-m-d\TH:i:s', '2015-04-20T18:56:42');
ISO8601无冒号

$dateTime = DateTime::createFromFormat('Y-m-d\TH:i:sO', '2015-04-20T18:56:42+0000');
带冒号的ISO8601

$date = $dateTime->format('c');
Salesforce ISO8601格式

DateTime::createFromFormat('Y-m-d\TH:i:s.uO', '2015-04-20T18:56:42.000+0000');


希望这能节省别人的时间

因为这并没有真正说明如何使用“z”选项将YYYY:DDD:HH:MM:SS时间转换为unix秒,所以您必须创建自己的函数来将DOY转换为月份和月份的日期。这就是我所做的:

function _IsLeapYear ($Year)
{
    $LeapYear = 0;
    # Leap years are divisible by 4, but not by 100, unless by 400
    if ( ( $Year % 4 == 0 ) || ( $Year % 100 == 0 ) || ( $Year % 400 == 0 ) ) {
        $LeapYear = 1;
    }
    return $LeapYear;
}

function _DaysInMonth ($Year, $Month)
{

    $DaysInMonth = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

    return ((_IsLeapYear($Year) && $Month == 2) ? 29 : $DaysInMonth[$Month - 1]);
}

function yydddhhssmmToTime($Year, $DOY, $Hour, $Min, $Sec)
{
   $Day = $DOY;
   for ($Month = 1;  $Day > _DaysInMonth($Year, $Month);  $Month++) {
    $Day -= _DaysInMonth($Year, $Month);
   }

   $DayOfMonth = $Day;

   return mktime($Hour, $Min, $Sec, $Month, $DayOfMonth, $Year);
}

$timeSec = yydddhhssmmToTime(2016, 365, 23, 23, 23);
$str = date("m/d/Y H:i:s", $timeSec);
echo "unix seconds: " . $timeis . " " . $str ."<br>";
function\u IsLeapYear($Year)
{
$LeapYear=0;
#闰年可以被4整除,但不能被100整除,除非被400整除
如果($Year%4==0)| |($Year%100==0)| |($Year%400==0)){
$LeapYear=1;
}
每年返回$1;
}
函数_DaysInMonth($Year,$Month)
{
$DaysInMonth=数组(31,28,31,30,31,30,30,31,31,30,31);
回报((_IsLeapYear($Year)和&$Month==2)?29:$DaysInMonth[$Month-1]);
}
函数yydddhhssmmToTime($Year、$DOY、$Hour、$Min、$Sec)
{
$Day=$DOY;
对于($Month=1;$Day>_DaysInMonth($Year,$Month);$Month++){
$Day-=\u DaysInMonth($Year,$Month);
}
$DayOfMonth=$Day;
返回mktime($Hour、$Min、$Sec、$Month、$DayOfMonth、$Year);
}
$timeSec=yyddhhsmmtotime(2016,365,23,23,23);
$str=日期(“m/d/Y H:i:s”,$timeSec);
回显“unix秒:”$时间是。" " . $str.“
”;
页面上的输出显示了它的工作状态,因为我可以将秒数转换回原始输入值。
unix秒:148314020312/30/2016 23:23:23

出于好奇,您的代码和else{$schedule=str_replace('/','-',$schedule);$schedule=date('Y-m-dh:i:s',strotime('schedule));}这可能是最好的解决方案,除非您能够更好地控制输入并确保使用。
strotime
不理解D/M/Y。它只能处理Y/M/D和M/D/Y。如果您尝试将D/M/Y传递给它,它将失败
strotime('20/02/2003')
返回
false
。您必须通过
'20.03.2003'
(注意点!)才能识别该格式,这不是您期望的日期格式。我知道strotime不喜欢
/
,但如果您将
/
转换为
-
,则它可以完美工作。我发现很难阅读上面的代码,介意对其稍加注释以解释每个函数的作用吗?看起来支持D-M-Y,但示例日期只包含斜杠。此外,虽然支持D-M-Y,但不支持M-D-Y——在M/D/Y上替换斜杠会导致日期不可解析。我会马上用更多的注释编辑我的代码。这是一个很好的答案。真的应该得到更多的选票!感谢对日期时间“M”的支持:
schedule\u format=str\u replace(数组('M','Y','M','d','H','i','a'),数组('%b','%Y','%M','%d','%i','%M','%p'),$dformat)有一个小错误,因为“H”应该替换为%H(24小时格式),而不是%I(12小时格式)。这是一个改进的行:
$schedule\u format=str\u replace(数组('M','Y','M','d','H','H','i','a'),数组('%b','%Y','%M','%d','%H','%M','%p'),$dformat)在Windows上不工作!,strptime未实施请阅读问题,请原谅,本打算在适用的问题上发布,但很高兴终于解决了问题,不知道如何删除此内容,我的错。这在5.2.x中不适用,通常采用非英语格式,如“d/m/Y”,但是如果用“-”替换“/”,它就可以工作了。正如5.2.x在近6年前达到的那样,我并不太担心它。无论如何,谢谢你让我知道。
function _IsLeapYear ($Year)
{
    $LeapYear = 0;
    # Leap years are divisible by 4, but not by 100, unless by 400
    if ( ( $Year % 4 == 0 ) || ( $Year % 100 == 0 ) || ( $Year % 400 == 0 ) ) {
        $LeapYear = 1;
    }
    return $LeapYear;
}

function _DaysInMonth ($Year, $Month)
{

    $DaysInMonth = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

    return ((_IsLeapYear($Year) && $Month == 2) ? 29 : $DaysInMonth[$Month - 1]);
}

function yydddhhssmmToTime($Year, $DOY, $Hour, $Min, $Sec)
{
   $Day = $DOY;
   for ($Month = 1;  $Day > _DaysInMonth($Year, $Month);  $Month++) {
    $Day -= _DaysInMonth($Year, $Month);
   }

   $DayOfMonth = $Day;

   return mktime($Hour, $Min, $Sec, $Month, $DayOfMonth, $Year);
}

$timeSec = yydddhhssmmToTime(2016, 365, 23, 23, 23);
$str = date("m/d/Y H:i:s", $timeSec);
echo "unix seconds: " . $timeis . " " . $str ."<br>";