Álvaro González
Álvaro González

Reputation: 146370

new DateTime returns empty DateTime instance

Tracking the source of a bug, I've found that this piece of code behaves differently in the development and live servers:

<?php

ini_set('log_errors', FALSE);
ini_set('display_errors', TRUE);
error_reporting(E_ALL ^ E_STRICT);

var_dump(date_default_timezone_set('Europe/Madrid'));

try{
    $dt = new DateTime('2010-12-01');
    var_dump($dt);
}catch(Exception $e){
    var_dump($e);
}

In my dev box (PHP/5.3.0) I get the expected output:

bool(true)
object(DateTime)#1 (3) {
  ["date"]=>
  string(19) "2010-12-01 00:00:00"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(13) "Europe/Madrid"
}

In the live server (PHP/5.2.14) I get a blank object:

bool(true)
object(DateTime)#1 (0) {
}

I've already discarded the usual suspects (missing default time zone, non-parseable date string...). This code has the same output in both servers:

<?php

ini_set('log_errors', FALSE);
ini_set('display_errors', TRUE);
error_reporting(E_ALL ^ E_STRICT);

var_dump(date_default_timezone_set('Europe/Madrid'));

$ts = strtotime('2010-12-01');
var_dump($ts, date('r', $ts));

Prints:

bool(true)
int(1291158000)
string(31) "Wed, 01 Dec 2010 00:00:00 +0100"

Am I missing something really obvious?

Upvotes: 1

Views: 4314

Answers (2)

Patrick Evans
Patrick Evans

Reputation: 42736

with PHP 5.2 you have to use.

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

Apparently you cant do a var_dump on the 5.2 version of DateTime. Probably had to do with how they had the class setup in 5.2

Upvotes: 7

Marek Sebera
Marek Sebera

Reputation: 40621

try to use this workaround used on 5.1/5.2 php

<?php
if (!class_exists('DateTime')) {
class DateTime {
public $date;

public function __construct($date) {
    $this->date = strtotime($date);
}

public function setTimeZone($timezone) {
    return;
}

private function __getDate() {
    return date(DATE_ATOM, $this->date);    
}

public function modify($multiplier) {
    $this->date = strtotime($this->__getDate() . ' ' . $multiplier);
}

public function format($format) {
    return date($format, $this->date);
}
}
}
?>

Upvotes: 0

Related Questions