PHPackages                             kachnitel/duration-bundle - 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. [Templating &amp; Views](/categories/templating)
4. /
5. kachnitel/duration-bundle

ActiveSymfony-bundle[Templating &amp; Views](/categories/templating)

kachnitel/duration-bundle
=========================

A Symfony bundle for handling duration parsing, formatting, and form integration. Parse human-readable duration strings (2h 30m, HH:MM:SS) and format seconds into readable formats.

v0.0.3(5mo ago)0153MITPHPPHP &gt;=8.2

Since Nov 26Pushed 5mo agoCompare

[ Source](https://github.com/kachnitel/duration-bundle)[ Packagist](https://packagist.org/packages/kachnitel/duration-bundle)[ RSS](/packages/kachnitel-duration-bundle/feed)WikiDiscussions master Synced 1mo ago

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

DurationBundle
==============

[](#durationbundle)

A Symfony bundle for handling duration parsing, formatting, and form integration. Parse human-readable duration strings (e.g., "2h 30m", "HH:MM:SS") and format seconds into readable formats.

Features
--------

[](#features)

- **Parse multiple duration formats**: "2h 30m", "2.5 hours", "90 minutes", "HH:MM", "HH:MM:SS"
- **Format durations**: Convert seconds to human-readable strings with customizable units
- **Symfony Form integration**: DurationType for seamless form handling
- **Twig filters**: Display durations in templates with ease
- **Flexible unit configuration**: Support for years, months, weeks, days, hours, minutes, seconds
- **Production-tested**: Extracted from real-world application code

Installation
------------

[](#installation)

Install the bundle via Composer:

```
composer require kachnitel/duration-bundle
```

If you're not using Symfony Flex, enable the bundle in `config/bundles.php`:

```
return [
    // ...
    Kachnitel\DurationBundle\DurationBundle::class => ['all' => true],
];
```

Usage
-----

[](#usage)

### 1. Service Usage

[](#1-service-usage)

The `DurationUtil` service provides static methods for duration manipulation:

```
use Kachnitel\DurationBundle\Service\DurationUtil;

// Parse duration strings to seconds
$seconds = DurationUtil::toSeconds('2h 30m');        // 9000
$seconds = DurationUtil::toSeconds('2.5 hours');     // 9000
$seconds = DurationUtil::toSeconds('90 minutes');    // 5400
$seconds = DurationUtil::toSeconds('02:30');         // 9000
$seconds = DurationUtil::toSeconds('02:30:45');      // 9045

// Format seconds to human-readable strings
$duration = DurationUtil::toString(9000);                    // "2h 30m"
$duration = DurationUtil::toString(9000, false);             // "2 hours 30 minutes"
$duration = DurationUtil::toString(9000, true, ['h', 'm']); // "2h 30m"

// Format as HH:MM
$time = DurationUtil::toHhMm(9000);  // "02:30"

// Convert between DateInterval and seconds
$interval = new DateInterval('PT2H30M');
$seconds = DurationUtil::intervalToSeconds($interval);  // 9000

$interval = DurationUtil::secondsToInterval(9000);  // DateInterval object
```

### 2. Form Integration

[](#2-form-integration)

Use `DurationType` in your forms to handle duration input:

```
use Kachnitel\DurationBundle\Form\Type\DurationType;

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('duration', DurationType::class, [
                'label' => 'Task Duration',
                'help' => 'Examples: 2h 30m, 90 minutes, 02:30',
                'required' => false,
            ]);
    }
}
```

In your entity, store the duration as an integer (seconds):

```
class Task
{
    #[ORM\Column(type: 'integer', nullable: true)]
    private ?int $duration = null;

    public function getDuration(): ?int
    {
        return $this->duration;
    }

    public function setDuration(?int $duration): self
    {
        $this->duration = $duration;
        return $this;
    }
}
```

The form type automatically:

- Converts seconds to human-readable format for display (e.g., "2h 30m")
- Parses user input back to seconds for storage

**Supported Input Formats:**

- `2h 30m` or `2h30m` - Hours and minutes with short units
- `2.5 hours` - Decimal with long unit names
- `90 minutes` or `90m` - Minutes only
- `02:30` - HH:MM format (interpreted as hours:minutes)
- `02:30:45` - HH:MM:SS format
- `9000` - Plain seconds

### 3. Twig Filters

[](#3-twig-filters)

Display durations in your templates using the provided Twig filters:

```
{# Format duration in short format #}
{{ task.duration|duration }}
{# Output: "2h 30m" #}

{# Format duration in long format #}
{{ task.duration|duration(false) }}
{# Output: "2 hours 30 minutes" #}

{# Format as HH:MM #}
{{ task.duration|hhmm }}
{# Output: "02:30" #}

{# Parse duration string to seconds #}
{{ "2h 30m"|toSeconds }}
{# Output: 9000 #}
```

Advanced Configuration
----------------------

[](#advanced-configuration)

### Custom Unit Selection

[](#custom-unit-selection)

You can specify which units to include when formatting:

```
use Kachnitel\DurationBundle\Service\DurationUtil;

// Only hours and minutes
$duration = DurationUtil::toString(93784, true, ['h', 'm']);  // "26h 3m"

// Days, hours, and minutes
$duration = DurationUtil::toString(93784, true, ['d', 'h', 'm']);  // "1d 2h 3m"

// All units
$duration = DurationUtil::toString(93784, true, ['y', 'mo', 'w', 'd', 'h', 'm', 's']);
// Output depends on the value
```

### Available Units

[](#available-units)

The bundle supports the following units (defined in `DurationUtil::UNIT_CONFIG`):

UnitShortLongSeconds`y`yyear/years31,536,000`mo`momonth/months2,592,000`w`wweek/weeks604,800`d`dday/days86,400`h`hhour/hours3,600`m`mminute/minutes60`s`ssecond/seconds1Examples
--------

[](#examples)

### Example 1: Time Tracking Application

[](#example-1-time-tracking-application)

```
// Entity
class TimeEntry
{
    #[ORM\Column(type: 'integer')]
    private int $duration = 0;
}

// Form
$builder->add('duration', DurationType::class, [
    'label' => 'Duration',
    'help' => 'Enter duration (e.g., 2h 30m)',
]);

// Template

    Duration: {{ entry.duration|duration }}

```

### Example 2: Task Estimation

[](#example-2-task-estimation)

```
{% if task.estimatedDuration %}

        Estimated: {{ task.estimatedDuration|hhmm }}

{% endif %}

{% if task.actualDuration %}

        Actual: {{ task.actualDuration|hhmm }}

{% endif %}
```

### Example 3: Service Layer

[](#example-3-service-layer)

```
use Kachnitel\DurationBundle\Service\DurationUtil;

class ReportGenerator
{
    public function generateTimeReport(array $tasks): array
    {
        $totalSeconds = array_sum(array_column($tasks, 'duration'));

        return [
            'total_time' => DurationUtil::toString($totalSeconds, false),
            'total_hours' => DurationUtil::toHhMm($totalSeconds),
            'task_count' => count($tasks),
            'average_time' => DurationUtil::toString($totalSeconds / count($tasks)),
        ];
    }
}
```

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Symfony 6.4 or 7.0+

Testing
-------

[](#testing)

Run the test suite:

```
composer install
vendor/bin/phpunit
```

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

This bundle is released under the MIT License. See the [LICENSE](LICENSE) file for details.

Credits
-------

[](#credits)

Developed by [Mr. Duck](https://github.com/kachnitel)

Extracted from production code and open-sourced for the Symfony community.

Support
-------

[](#support)

If you encounter any issues or have questions:

- Open an issue on [GitHub](https://github.com/kachnitel/duration-bundle/issues)
- Check existing issues for solutions

Changelog
---------

[](#changelog)

### 1.0.0 (Initial Release)

[](#100-initial-release)

- Duration parsing from multiple formats
- Duration formatting with customizable units
- Symfony Form integration (DurationType)
- Twig filters (duration, toSeconds, hhmm)
- DateInterval conversion utilities
- Full test coverage

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance70

Regular maintenance activity

Popularity13

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity39

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% 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 ~0 days

Total

3

Last Release

173d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1206e3a106f8c82c1dd68d4304c951d6979f39e5806de2a7a72724d825f06b38?d=identicon)[kachnitel](/maintainers/kachnitel)

---

Top Contributors

[![kachnitel](https://avatars.githubusercontent.com/u/4067705?v=4)](https://github.com/kachnitel "kachnitel (3 commits)")

---

Tags

symfonytwigtimeformintervalduration

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/kachnitel-duration-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/kachnitel-duration-bundle/health.svg)](https://phpackages.com/packages/kachnitel-duration-bundle)
```

###  Alternatives

[a2lix/auto-form-bundle

Automate form building

873.8M11](/packages/a2lix-auto-form-bundle)[boekkooi/jquery-validation-bundle

Jquery form validation bundle for symfony 2

2773.9k1](/packages/boekkooi-jquery-validation-bundle)[nucleos/antispam-bundle

This bundle provides some basic features to reduce spam in symfony forms.

52105.1k](/packages/nucleos-antispam-bundle)[yellowskies/qr-code-bundle

Symfony Barcode &amp; QR Code Generator Bundle with Twig extension

36682.9k](/packages/yellowskies-qr-code-bundle)[eschmar/time-ago-bundle

Provides a simple twig filter for expressing time difference in words.

1851.4k](/packages/eschmar-time-ago-bundle)[nurikabe/star-rating-bundle

Symfony form type and Twig extension for quick integration of FyneWorks' Star Rating widget

113.1k](/packages/nurikabe-star-rating-bundle)

PHPackages © 2026

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