PHPackages                             demirkaric/php-duration-formatter - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. demirkaric/php-duration-formatter

ActiveLibrary

demirkaric/php-duration-formatter
=================================

A PHP library for parsing and formatting time durations.

v1.0.3(4mo ago)310.9k↑28.6%1MITPHPPHP ^8.2CI passing

Since May 24Pushed 4mo agoCompare

[ Source](https://github.com/demirkaric/php-duration-formatter)[ Packagist](https://packagist.org/packages/demirkaric/php-duration-formatter)[ RSS](/packages/demirkaric-php-duration-formatter/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (1)Versions (6)Used By (0)

📦 php-duration-formatter
========================

[](#-php-duration-formatter)

[![PHPUnit](https://github.com/demirkaric/php-duration-formatter/actions/workflows/phpunit.yml/badge.svg)](https://github.com/demirkaric/php-duration-formatter/actions/workflows/phpunit.yml)[![Coverage Status](https://camo.githubusercontent.com/553c2f3aae6006aaae5d99fb1e9a31297ca7bd535eda517cbeb95f7160187635/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f64656d69726b617269632f7068702d6475726174696f6e2d666f726d61747465722f62616467652e7376673f6272616e63683d666561742d7374617469632d696e7374616e6365)](https://coveralls.io/github/demirkaric/php-duration-formatter?branch=feat-static-instance)[![PHP](https://camo.githubusercontent.com/b5d4f7901c58ad1ddfff679966f426cc25a9354bab763846b9a7276c2feab4e0/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253545382e322d626c7565)](https://camo.githubusercontent.com/b5d4f7901c58ad1ddfff679966f426cc25a9354bab763846b9a7276c2feab4e0/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253545382e322d626c7565)[![License](https://camo.githubusercontent.com/d6bc2b26794002c24d023acaab01b6dbb953c57ab9cb80ba5b8aa2f2bd5de99a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d626c7565)](https://camo.githubusercontent.com/d6bc2b26794002c24d023acaab01b6dbb953c57ab9cb80ba5b8aa2f2bd5de99a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d626c7565)

**Advanced PHP library for parsing, formatting, converting, and humanizing time durations.**

Supports intuitive input formats like `1h 30m`, `01:30:00`, `5400`, or **ISO 8601** (`PT1H30M`, `P1DT2H`) and provides custom formatting, JSON serialization, and accurate conversion to seconds and minutes.

> 🛠️ Built as an enhanced and modernized alternative to [kevinkhill/php-duration](https://github.com/kevinkhill/php-duration), offering expanded feature support, token-based formatting, custom hours-per-day handling, and complete PHPUnit test coverage.

---

✅ Features:
-----------

[](#-features)

- Flexible input support: parse durations from strings, numbers, or colon-formatted time
- **ISO 8601 duration format support** (parsing and formatting)
- Conversion to seconds, minutes, arrays, strings, and JSON
- Custom formatting with tokens (`d`, `hh`, `mm`, `ss`, etc.)
- Support for days with customizable `hoursPerDay`
- Human-readable output (`1h 30m`)
- Chainable and reusable instance
- Implements `JsonSerializable` and `Stringable`
- Fully tested with 94+ % PHPUnit coverage

---

📥 Installation
--------------

[](#-installation)

Install via [Composer](https://getcomposer.org):

```
composer require demirkaric/php-duration-formatter
```

---

🚀 Usage
-------

[](#-usage)

### ✅ Basic Usage

[](#-basic-usage)

```
use Demirk\PhpDurationFormatter\TimeDuration;

$duration = new TimeDuration('1h 42m 30s');

echo $duration->toSeconds();      // 6150.0
echo $duration->toMinutes();      // 102.5
echo $duration->humanize();       // "1h 42m 30s"
echo $duration->format();         // "01:42:30" (default format)
echo (string) $duration;          // "01:42:30"

echo json_encode($duration);      // {"seconds":6150,"values":{"days":0,"hours":1,"minutes":42,"seconds":30},"formatted":"01:42:30","humanized":"1h 42m 30s"}
```

---

### 🧩 Supported Input Formats

[](#-supported-input-formats)

- `"1h 30m"`
- `"1d 4h 5m 2.5s"`
- `"01:30"` or `"01:30:45"`
- `3600` or `3661.5`
- `"2d"`
- **ISO 8601 durations**: `"PT1H30M"`, `"P1DT2H"`, `"P2W"`

---

### 🌐 ISO 8601 Duration Support

[](#-iso-8601-duration-support)

The library fully supports **ISO 8601 duration format** for both parsing and formatting.

#### Parsing ISO 8601 Durations

[](#parsing-iso-8601-durations)

```
use Demirk\PhpDurationFormatter\TimeDuration;

// Time only
$duration1 = new TimeDuration('PT1H30M');
echo $duration1->toSeconds();    // 5400.0
echo $duration1->humanize();     // "1h 30m"

// Date and time
$duration2 = new TimeDuration('P1DT2H30M');
echo $duration2->toSeconds();    // 95400.0
echo $duration2->humanize();     // "1d 2h 30m"

// Weeks (converted to days)
$duration3 = new TimeDuration('P2W');
echo $duration3->toSeconds();    // 1209600.0
echo $duration3->humanize();     // "14d"

// Decimal values
$duration4 = new TimeDuration('PT2.5H');
echo $duration4->humanize();     // "2h 30m"
```

#### Formatting to ISO 8601

[](#formatting-to-iso-8601)

```
$duration = new TimeDuration('1d 2h 30m 45s');
echo $duration->toIso8601();     // "P1DT2H30M45S"

$duration2 = new TimeDuration('5h 30m');
echo $duration2->toIso8601();    // "PT5H30M"
```

**Supported ISO 8601 Components:**

- `P` - Period designator (required)
- `nD` - Days
- `T` - Time designator
- `nH` - Hours
- `nM` - Minutes
- `nS` - Seconds
- `nW` - Weeks (converted to days)

> 💡 **Note**: Weeks are normalized to days (e.g., `P1W` becomes `P7D` when formatting).

---

🧠 Custom Format Tokens
----------------------

[](#-custom-format-tokens)

Use `format(string $pattern)` to generate custom formatted strings.

TokenMeaningExample`d`Days (non-padded)1`dd`Days (zero-padded)01`h`Hours (non-padded)2`hh`Hours (zero-padded)02`H`Total hours (including days)26`HH`Total hours (zero-padded)26`m`Minutes5`mm`Minutes (zero-padded)05`s`Seconds4.5`ss`Seconds (zero-padded)04.5`S`Rounded seconds4`SS`Rounded seconds (zero-padded)04```
$duration = new TimeDuration('1d 2h 5m 30s');

echo $duration->format('dd hh:mm:ss'); // 01 02:05:30
echo $duration->format('H:mm');        // 26:05
```

> ⚠️ `format()` will throw an exception if both `d` and `H` are used together (conflict between relative and absolute hours).

---

🔄 Conversion Methods
--------------------

[](#-conversion-methods)

```
$duration->toSeconds();                // float/int
$duration->toSeconds('1h 5s');         // pass string directly
$duration->toMinutes();                // in float
$duration->toMinutes(null, 0);         // rounded to int
$duration->toMinutes(null, 2);         // rounded to 2 decimal places
```

---

📚 Humanized Output
------------------

[](#-humanized-output)

```
$duration = new TimeDuration('2d 3h 15m');

echo $duration->humanize(); // "2d 3h 15m"
```

---

🧪 Tests
-------

[](#-tests)

This library is tested with [PHPUnit](https://phpunit.de):

- ✅ Covers parsing, formatting, rounding, edge cases, and serialization

To run tests:

```
vendor/bin/phpunit
```

---

👏 Credits
---------

[](#-credits)

This library is inspired by and originally based on [Kevin Hill’s `php-duration`](https://github.com/kevinkhill/php-duration), with significant improvements in architecture, extensibility, and formatting capabilities.
Parsing, formatting, and conversion logic has been modernized and tested.

---

📄 License
---------

[](#-license)

MIT © Demir Karić
See `LICENSE` file for details.

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance77

Regular maintenance activity

Popularity30

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 51.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~78 days

Total

4

Last Release

124d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/817741302bb46efcffd06fba7473ad7c7916551f02b0278b9fed2b7d57eca233?d=identicon)[demirkaric](/maintainers/demirkaric)

---

Top Contributors

[![maniaba](https://avatars.githubusercontent.com/u/61078470?v=4)](https://github.com/maniaba "maniaba (15 commits)")[![demirkaric](https://avatars.githubusercontent.com/u/19651216?v=4)](https://github.com/demirkaric "demirkaric (13 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/demirkaric-php-duration-formatter/health.svg)

```
[![Health](https://phpackages.com/badges/demirkaric-php-duration-formatter/health.svg)](https://phpackages.com/packages/demirkaric-php-duration-formatter)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
