PHP code example of wookieb / relative-date

1. Go to this page and download the library: Download wookieb/relative-date 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/ */

    

wookieb / relative-date example snippets


$formatter = new Wookieb\RelativeDate\Formatters\BasicFormatter();
// You can pick one of calculators. See "calculators" section for details
$calculator = Wookieb\RelativeDate\Calculators\TimeAgoDateDiffCalculator::full();

$date = new \DateTime('2016-01-01 14:00:00');
$now = new \DateTime('2016-01-01 16:00:00'); // not 

// $translator - get Symfony translator somehow 
$formatter = new Wookieb\RelativeDate\Formatters\TranslatorFormatter($translator);
$calculator = Wookieb\RelativeDate\Calculators\TimeAgoDateDiffCalculator::full();

$date = new \DateTime('2016-01-01 14:00:00');
$now = new \DateTime('2016-01-01 16:00:00');
$formatter->format($calculator->compute($date, $now)); // 2 godziny temu

$translator = new TranslatorFormatter($translator);
$translator->registerCustomPlaceholder(
    ['yesterday', 'tomorrow'], // applies only to specific result key names
    '%at%', // placeholder name
    function(DateDiffResult $result) {
        return $result->getRequest()
            ->getDate()
            ->format('H:i');
    }
);

// translation definition
tomorrow: tomorrow at %at%

// usage
$date = new \DateTime('2016-01-01 14:05:00');
$baseDate = new \DateTime('2016-01-02 00:00:00');
$result = $translator->format(TimeAgoCalculator::upTo2Weeks()->compute($date, $baseDate));
$result; // yesterday at 14:05
`
$format = Wookieb\RelativeDate\Formatters\BasicFormatter::SHORT_FORMAT; // Y-m-d
$formatter = new Wookieb\RelativeDate\Formatters\BasicFormatter($format);
$calculator = Wookieb\RelativeDate\Calculators\TimeAgoDateDiffCalculator::upTo2Weeks();

$date = new \DateTime('2016-01-01 14:00:00');
$now = new \DateTime('2016-03-01 16:00:00');
$formatter->format($calculator->compute($date, $now)); // 2016-01-01