Richard Ybias
Richard Ybias

Reputation: 335

Datetime Difference Error

I have a problem when I use difference of the datetime.

Here is the php code

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->days;

The correct result should be 2. But unfortunately it results 6015. Even when I change the date, its still 6015. Did you guys encounter this problem? I tried to run the script from other computer but its working.

Upvotes: 2

Views: 608

Answers (3)

Tony Stark
Tony Stark

Reputation: 8084

Try this,

$start_date = new DateTime("2009-10-11");
$end_date = new DateTime("2009-10-13");
$interval = $start_date->diff($end_date);
echo "Result " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";

you use $interval->days replace with $interval->d." days "

you can check my answer https://stackoverflow.com/a/14938421/718224 on date difference for more information.

may this help you.

Upvotes: 1

M.I.T.
M.I.T.

Reputation: 1042

yes sure man for that you need to assign timezone

try this code i set it for india

$MNTTZ = new DateTimeZone('Asia/Kolkata');
$datetime1 = new DateTime('2009-10-11',$MNTTZ);
$datetime2 = new DateTime('2009-10-13',$MNTTZ);
$interval = $datetime1->diff($datetime2);
echo $interval->days;

Upvotes: 2

Ikong
Ikong

Reputation: 2570

make sure to set format()

 <?php
    $datetime1 = date_create('2009-10-11');
    $datetime2 = date_create('2009-10-13');
    $interval = date_diff($datetime1, $datetime2);
    echo $interval->format('%R%a days');
    ?>

see here...

Upvotes: 0

Related Questions