简体   繁体   中英

Strange behaviour of PHP DateTime Class

I'm trying to get the time difference in milliseconds.

$_SESSION['startTime'] = time();
$to_time = time();

//I call the code from here after a delay, say 4 seconds

$from_time = $_SESSION['startTime'];
$d1 = new DateTime($from_time);
$d2 = new DateTime($to_time);


print_r( $d1->diff($d2));

I print the result after 4 seconds and the result is somewhat like this:

DateInterval Object
(
    [y] => 4 //---- Problem, this value should be +
    [m] => 0 //                                   |
    [d] => 0 //                                   |
    [h] => 0 //                                   |       
    [i] => 0 //                                   |
    [s] => 0 //<-here-----------------------------+
    [invert] => 1
    [days] => 1461
)

[s] should have been 4. why the 4 is in the year section? What am I doing wrong?

UPDATE - Solved

$to_time = (microtime(true));
$from_time = ( $_SESSION['startTime']);
$diff = $to_time - $from_time;
print $diff;

Prints

3.xxxxxx

You must specify the formatting. You're sending in a unix timestamp into DateTime, therefor:

$d1 = new DateTime($from_time);
$d2 = new DateTime($to_time);

Becomes

$d1 = new DateTime('@'.$from_time);
$d2 = new DateTime('@'.$to_time);

The @ symbol tells DateTime that I'm using a Unix Timestamp.

The constructor for DateTime accepts a string as a parameter not a timestamp, which is why you are seeing the "strange behaviour".

You need to expressly set the timestamp after insantiating a DateTime object:-

$from_time = $_SESSION['startTime'];
$d1 = new DateTime();
$d1->setTimestamp($from_time);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM