我正在尝试将日期转换为DateTime对象。我的代码在我的localhost(php版本5.3)上工作正常但在我的远程服务器上返回一个空白的DateTime对象(php版本5.2.14)。我错过了一些非常明显的东西吗?
<?php
$d = '2010-01-01';
$n = new DateTime ( $d );
print_r($n);
?>
//在localhost上生成:
DateTime Object ( [date] => 2010-01-01 00:00:00 [timezone_type] => 3 [timezone] => UTC )
//结果在remotehost:
DateTime Object ( ) // is blank
更新示例::
也许我错过了一些非常简单的事情。我已经尝试过Pooyan的建议,但我必须密集:
function changeDate ( ){
$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
答案 0 :(得分:2)
你必须使用:
$d = '2010-01-01';
$n = new DateTime ( $d )
echo $n->format('Y-m-d');
答案 1 :(得分:0)
$v->format('Y-m-d')
不会更改对象,但会返回一个字符串,其中DateTime以给定格式格式化。
所以这应该有效:
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());
虽然这样可以返回输入数组,所以它毫无意义。
答案 2 :(得分:0)
这个回复可能来得太迟了。我遇到了同样的问题,问题出在print_r
,而不是DateTime
对象本身。似乎在PHP 5.2上的DateTime对象中使用print_r
和/或var_dump
不起作用。因此有关使用
echo $n->format('Y-m-d'); // (1)
而不是
print_r($n)
如果(1)显示预期值,那么您的对象就可以了。
您可以在此处找到更多信息: new DateTime returns empty DateTime instance
答案 3 :(得分:-1)
您应该知道有一个名为getLastErrors()
的方法可以保存使用DateTime
尝试以下方法:
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');
}
}
看看是否会有所启发。