Andrii H.
Andrii H.

Reputation: 1812

PHP Consider using \DateTime for dst safe datetime manipulation

I have a php script, that:

  1. Gets old timestamp from database
  2. Gets current time timestamp with time() function
  3. Gets difference between them by $curr - $got

And now I need to convert that difference seconds to minutes/hours/days. I have done it for minutes and hours already. But when I try to divide difference by 86400, IDE shows error:

PHP Consider using \DateTime for dst safe datetime manipulation

How can I fix that?

P.S. Here is a php script:

$curr = time();
$got = '1503079200'; //*Think, that this value is returned from* database row
$difference = $curr - $got;
$hrdifference= '';
$type = '';

if ( $difference >= 86400 ) {
    $type = 'day';
    $hrdifference = $difference/86400; //**Here it throws error**
} elseif ( $difference >= 3600 ) {
    $type = 'hour';
    $hrdifference = $difference/3600;
} elseif ( $difference >= 60 ) {
    $type = 'minutes';
    $hrdifference = $difference/60;
} elseif ( $difference < 60 ) {
    $type = 'seconds';
    $hrdifference = $difference;
}

echo $hrdifference . ' ' . $type;

Upvotes: 3

Views: 1156

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

Instead of doing this much i will do it in below way:-

<?php
// $curr = time(); // not needed
$got = '1503079200'; //value is returned from database row

$datetime1 = new DateTime(); // current date-time
$datetime2 = new DateTime(date('Y-m-d',$got)); // get date-time based on $got
$interval = $datetime1->diff($datetime2); // get difference
echo $interval->format('%d')." days ".$interval->format('%h')." Hours ".$interval->format('%i')." Minutes"; //print days hour minute

Output:- https://eval.in/850420

Upvotes: 5

Related Questions