PHP uses the string value of the SimpleXMLElement
if you use it in intval
or as well directly in numeric calculations (which also cast to int).
As I already commented, my first quick guess was right, it truncates the number than to the maximum integer available on a 32 bit system signed (231 − 1) (I guess you're using one) which results in:
2 147 483 647
25-01-1970
This number btw. is sort of somewhat famous and has it's own Wikipedia page: 2147483647.
Instead use the floatval
function, it gives you what you're looking for:
$seconds = floatval($start) / 1000;
echo date("d-m-Y", $seconds); # prints "30-04-2012"
Bonus: Here is some code you might find handy to have the conversion code in a central place and easily make use of:
/**
* Class MySimpleXMLElement
*
* Extended SimpleXMLElement
*/
class MySimpleXMLElement extends SimpleXMLElement
{
/**
* @param string $format
*
* @return bool|string
*/
public function getDateFromMilliseconds($format = "d-m-Y") {
return date("d-m-Y", floatval($this) / 1000);
}
/**
* @param DateTimeZone $timezone
*
* @return DateTime
*/
public function createDateTimeFromMilliseconds(DateTimeZone $timezone = NULL) {
return new DateTime('@' . (floatval($this) / 1000), $timezone);
}
}
$data = new MySimpleXMLElement('<r><est__start>1335744000000</est__start><est__end>1342742400000</est__end></r>');
/* @var $start MySimpleXMLElement */
$start = $data->est__start;
echo $start->getDateFromMilliseconds(), "\n"; # prints "30-04-2012"
echo $start->createDateTimeFromMilliseconds()->format('Y-m-d'); # prints "2012-04-30"
It works by extending from SimpleXMLElement and adding the date-creation functions, here one for a formatted string and for more advanced datetime operations one that gives back a DateTime
object.
Last time I extended SimpleXMLElement on Stackoverflow was in an answer to the "How to replace XML node with SimpleXMLElement PHP" question.