PHP code example of nyomanjyotisa / human-readable-time-diff

1. Go to this page and download the library: Download nyomanjyotisa/human-readable-time-diff library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nyomanjyotisa / human-readable-time-diff example snippets


use HumanReadableTimeDiff\TimeDifference;
use DateTime;

$timeDifference = new TimeDifference();
$timestamp = new DateTime('-2 hours');
echo $timeDifference->getDifference($timestamp); // Outputs: "2 hours ago"

use HumanReadableTimeDiff\TimeDifference;
use DateTime;

$referenceTime = new DateTime('2023-01-01 12:00:00');
$timeDifference = new TimeDifference($referenceTime);
$timestamp = new DateTime('2023-01-01 10:00:00');
echo $timeDifference->getDifference($timestamp); // Outputs: "2 hours ago"

use HumanReadableTimeDiff\TimeDifference;
use HumanReadableTimeDiff\TranslatedTimeFormatter;
use DateTime;

// Spanish
$formatter = new TranslatedTimeFormatter('es');
$timeDifference = new TimeDifference(null, $formatter);
$timestamp = new DateTime('-1 day');
echo $timeDifference->getDifference($timestamp); // Outputs: "1 día atrás"

// French
$formatter = new TranslatedTimeFormatter('fr');
$timeDifference = new TimeDifference(null, $formatter);
$timestamp = new DateTime('-2 hours');
echo $timeDifference->getDifference($timestamp); // Outputs: "il y a 2 heures"

use HumanReadableTimeDiff\TimeFormatterInterface;

class CustomTimeFormatter implements TimeFormatterInterface
{
    public function formatSeconds(int $seconds): string
    {
        return $this->formatUnit($seconds, 'second');
    }

    // Implement other methods...

    private function formatUnit(int $value, string $unit): string
    {
        // Your custom formatting logic
    }
}