-1

so hello i am trying to use this most used php script linked here Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago... but i cannot get it working, i thought i would fill variable with $datetime with the date i want to differente with i am inputting date with this format "1614084957" but yet i get error

Error: Uncaught Error: Class 'datetime' not found in

i dont know what wrong its included the function is above the desired echo

            function time_elapsed_string($datetime, $full = false) {
                $now = new DateTime;
                $ago = new DateTime($datetime);
                $diff = $now->diff($ago);
            
                $diff->w = floor($diff->d / 7);
                $diff->d -= $diff->w * 7;
            
                $string = array(
                    'y' => 'year',
                    'm' => 'month',
                    'w' => 'week',
                    'd' => 'day',
                    'h' => 'hour',
                    'i' => 'minute',
                    's' => 'second',
                );
                foreach ($string as $k => &$v) {
                    if ($diff->$k) {
                        $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
                    } else {
                        unset($string[$k]);
                    }
                }
            
                if (!$full) $string = array_slice($string, 0, 1);
                return $string ? implode(', ', $string) . ' ago' : 'just now';
            }


if ($page->id == 1) {
    $kat = $pages->get('/kategorie/');
    include('chunks/hry.php');
}

in hry.php i jsut have som foreach and ifs i have foreach for each a link to game a i wanted to use this function to determine when this game was created,

Paul T.
  • 4,703
  • 11
  • 25
  • 29
Picarica
  • 23
  • 4
  • 1
    I'm just guessing ( because you didn't provide the framework used ) that you are using namespaces in your code. If yes, then you need to use fully qualified class name `$now = new \DateTime;` – Samir Selia Jun 26 '21 at 13:49

1 Answers1

0

Add \ before your class name

$now = new \DateTime;
$ago = new \DateTime($datetime);
Mohammad
  • 132
  • 1
  • 7
  • hello so i hope i understand correctly so i had to add these in the function i copied ? if so i did that but now i got different error now the function starts like this `function time_elapsed_string($datetime, $full = false) { $now = new \DateTime; $ago = new \DateTime($datetime); $diff = $now->diff($ago);` and then i have `$ago = $page->created; echo time_elapsed_string($ago);` now echo $ago outputs date in this format **1614084957** which is good i hope and lastly i get this error Exception: DateTime::__construct(): Failed to parse time string (1614084957) at position 7 (9): – Picarica Jul 06 '21 at 09:09
  • 1
    nvm fixed it by adding `echo time_elapsed_string('@'.$ago);` – Picarica Jul 06 '21 at 09:13