nyomanjyotisa / human-readable-time-diff
A PHP package for converting timestamps into human-readable time differences
Requires
- php: >=7.4
Requires (Dev)
- phpstan/phpstan: ^1.9
- phpunit/phpunit: ^9.5
README
A PHP package for converting timestamps into human-readable time differences (e.g., "2 minutes ago", "3 hours ago", "1 day ago").
Requirements
- PHP 7.4 or higher
Installation
composer require nyomanjyotisa/human-readable-time-diff
Usage
Basic Usage
use HumanReadableTimeDiff\TimeDifference; use DateTime; $timeDifference = new TimeDifference(); $timestamp = new DateTime('-2 hours'); echo $timeDifference->getDifference($timestamp); // Outputs: "2 hours ago"
Using a Custom Reference Time
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"
Using Different Languages
The package supports multiple languages out of the box:
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"
Supported Languages
The package supports 50+ locale codes. You can call TranslationConfig::getAvailableLocales()
to retrieve the full list. Some examples include:
- en, id, es, fr, de, it, pt, ru, zh, ja, ko
- ar, hi, bn, tr, nl, pl, uk, vi, th, ms
- fa, ur, pa, gu, ta, te, kn, ml, mr, or, as
- ne, si, my, km, lo, bo, dz, ug, kk, ky, uz, tk
- az, ka, hy, he, yi, am, ti, om, so, sw, zu
- xh, st, tn, ts, ss, nr, nd, ve
For the complete list, refer to TranslationConfig::getAvailableLocales()
.
Creating Custom Formatters
You can create custom formatters by implementing the TimeFormatterInterface
:
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 } }
Testing
composer test
License
This package is licensed under the MIT License.
Hire the Author
Nyoman Jyotisa is a senior developer (PHP, JS, TS, Laravel, ReactJS, React Native, Next.js). Hire me at $20/hour.
Email: jyotisa1616@gmail.com