在5.2中的php dateTime :: createFromFormat?

时间:2011-03-22 23:20:20

标签: 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升级)。

6 个答案:

答案 0 :(得分:20)

只需包含下一个代码

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

答案 1 :(得分:9)

由于strtotime在面对D / M / Y时效果不佳且date_create_from_format不可用,strptime可能是您唯一的希望。它做了一些相当古老的学校的事情,比如处理多年,好像它们是自1900年以来的年数,处理几个月,好像一月是零月。这是一些可怕的示例代码,使用sprintf将日期重新组合成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');

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

答案 2 :(得分:6)

我认为扩展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。

请点击此处查看演示http://3v4l.org/djucq

答案 3 :(得分:0)

由于这并没有真正展示如何使用“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>";

页面上的输出显示其工作,因为我可以将秒转换回原始输入值。 unix秒:1483140203 12/30/2016 23:23:23

答案 4 :(得分:-1)

$your_datetime_object=new DateTime($date);
$date_format_modified=date_format($your_datetime_object,'D M d Y');//Change the format of date time

我在5.2的生产服务器上遇到了类似的问题,所以我使用上面的日期时间来创建一个对象,然后将格式更改为我喜欢的格式。

答案 5 :(得分:-1)

仅限日期和时间

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

希望这能节省时间!