开发者

DateTime object is blank

开发者 https://www.devze.com 2023-02-05 12:11 出处:网络
I am trying to convert a date to a DateTime Object. My code works fine on my localhost (php version 5.3) but returns a blank DateTime object on my remote server (php version 5.2.14). Am I missing some

I am trying to convert a date to a DateTime Object. My code works fine on my localhost (php version 5.3) but returns a blank DateTime object on my remote server (php version 5.2.14). Am I missing something really obvious?

<?php
   $d = '2010-01-01';
   $n = new DateTime ( $d );
   print_r($n);   
?>

// result on localhost:

 DateTime Object ( [date] => 2010-01-01 00:00:00 [timezone_type] => 3 [timezone] => UTC )

// result on remotehost:

 DateTime Object ( ) // is blank

UPDATED EXAMPLE::

Maybe I'm missing something really simple. I've tried it w/ the suggestion from Pooyan but I must be dense:

function changeDate开发者_Go百科 (  ){

$arr = array('2010-01-01' , '2010-01-02' , '2010-01-03');

foreach ( $arr as $k=>$v ){
    $v = new DateTime ( $v );
    $v->format('Y-m-d');
    $arr[$k] = $v;
}

return $arr;  

}

print_r( changeDate( ) ); // works in php 5.3 but still returns a blank DateTime Object in php 5.2


with PHP 5.2 you have to use:

$d = '2010-01-01';
$n = new DateTime ( $d )
echo $n->format('Y-m-d');  


$v->format('Y-m-d') doesn't change the object but returns a string with the DateTime formatted in the given format.

So this should work:

function changeDate () {
    $input = array('2010-01-01' , '2010-01-02' , '2010-01-03');

    foreach($input as $v) {
        $date = new DateTime($v);
        $output[] = $date->format('Y-m-d');
    }

    return $output;  
}

print_r(changeDate());

Although that gives you the input array back, so it's pretty pointless.


Probably this reply is arriving too late. I was having the same issue, and the problem was in print_r, not in the DateTime object itself. It seems using print_r and/or var_dump in DateTime objects on PHP 5.2 doesn't work. Hence the suggestion about using

echo $n->format('Y-m-d'); // (1)

instead of

print_r($n)

If (1) shows the expected value, then your object is fine.

You can find more info here: new DateTime returns empty DateTime instance


you should be aware that there is a method called getLastErrors() that would hold any errors created with DateTime

try the following:

foreach ($rows as $key => $value)
{
    if(isset( $value['date']))
    {
         try
         {
             $rows[$key]['date'] = new DateTime($value['date']);
             if(count(($e = $rows[$key]['date']->getLastErrors())) > 0)
             {
                   throw new Exception($e[0]);
             }
         }catch(Exception $e)
         {
             echo "Error: " . $e->getMessage();
             continue;
         }
         date_default_timezone_set('America/New_York');
    }
}

and see if that sheds some light.

0

精彩评论

暂无评论...
验证码 换一张
取 消