Working with durations made easy

Overview

Duration for PHP

Working with durations made easy.

Current version Supported PHP version Code Coverage Sponsor

Do you like to use DateInterval to compute and work with durations? Me neither, so let's fix that!


Installation

You can install the package with Composer:

composer require gamez/duration

You can then use Duration:

<?php
use Gamez\Duration;

$duration = Duration::make('13 minutes 37 seconds');
// or start with nothing
$duration = Duration::none();

Reference

Supported input values

DateIntervals

use Gamez\Duration;

Duration::make('PT13M37S');
Duration::make(new DateInterval('PT13M37S'));

Colon notation

use Gamez\Duration;

Duration::make('13:37'); // minutes:seconds
Duration::make('13:37:37'); // hours:minutes:seconds

Textual notation

A textual notation is any value that can be processed by DateInterval::createFromDateString()

use Gamez\Duration;

Duration::make('13 minutes 37 seconds');

Transformations

When transformed, a Duration will be

  • converted to a DateInterval representation
  • optimized in the sense that an input value of 60 seconds would result in an output value of "1 minute", for example "PT60S" would be converted to "PT1H"
use Gamez\Duration;

$duration = Duration::make('8 days 29 hours 77 minutes');

echo (string) $duration; // P9DT6H17M
echo json_encode($duration); // "P9DT6H17M"

Comparisons

use Gamez\Duration;

$oneSecond = Duration::make('1 second');
$sixtySeconds = Duration::make('60 seconds');
$oneMinute = Duration::make('1 minute');
$oneHour = Duration::make('1 hour');

$oneSecond->isSmallerThan($oneMinute); // true
$oneHour->isLargerThan($oneMinute); // true
$oneMinute->equals($sixtySeconds); // true

$durations = [$oneMinute, $oneSecond, $oneHour, $sixtySeconds];

usort($durations, function ($a, $b) {
    return $a->compareTo($b);
}); // -> [$oneSecond, $sixtySeconds, $oneMinute, $oneHour]

Operations

Results will always be rounded by the second.

use Gamez\Duration;

$thirty = Duration::make('30 seconds');

echo $thirty->withAdded('31 seconds'); // PT1M1S
echo $thirty->withSubtracted('29 seconds'); // PT1S
echo $thirty->multipliedBy(3); // PT1M30S
echo $thirty->dividedBy(2.5); // PT12S

$thirty->multipliedBy(-1); // InvalidArgumentException
$thirty->withSubtracted('31 seconds'); // InvalidArgumentException

Roadmap

  • Support more input formats
  • Add "output for humans" (like colon notation)
  • Support precision (similar to spatie/period)
  • ...
You might also like...
Sending Email via Microsoft Exchange Web Services made Easy!

Send Mail via Exchange Web Services! Sending Email via Microsoft Exchange Web Services (EWS) made easy! Installation Install via Composer composer req

Feature Switching made easy in Laravel 5

Feature Switching (made easy) for Laravel Need to wrap new features for dev and production? Use a directive in the view or alias in the controller The

Eloquent model-caching made easy.
Eloquent model-caching made easy.

Model Caching for Laravel Supporting This Package This is an MIT-licensed open source project with its ongoing development made possible by the suppor

Database version control, made easy!

Database version control, made easy! dbv.php is a database version control web application featuring schema management, revision scripts, and more! Ch

Nebula is a minimalistic and easy to use administration tool for Laravel applications, made with Laravel, Alpine.js, and Tailwind CSS.

Nebula Nebula is a minimalistic and easy to use administration tool for Laravel applications, made with Laravel, Alpine.js, and Tailwind CSS. Nebula m

Laravel Integration for Switchover PHP SDK. Feature Toggle Management made easy.

Switchover Laravel Integration Switchover Switchover is a Software-As-A-Service for managing feature toggles (aka switches, flags or feature flips) in

An Easy, Customizable & Open Source Robux Rewards Website Made With Laravel
An Easy, Customizable & Open Source Robux Rewards Website Made With Laravel

RbxDream - Robux Earning Rewards Website Coming Soon Current repo not stable. This is an open source Robux rewards site. Understanding Core Concepts T

A working Firebase http client
A working Firebase http client

PHP library access Firebase RESTful API Installation $ composer require jaredchu/jc-firebase-php Usage Generate a private key in JSON format. Check Fi

A set of utilities for working with vk api!

vk-utils Документация на русском языке Installation composer require labile/vk-utils How to use it? Simple example use Astaroth\VkUtils\Client; $api

A plugin for working with popular money libraries in Pest

This package is a plugin for Pest PHP. It allows you to write tests against monetary values provided by either brick/money or moneyphp/money using the same declarative syntax you're used to with Pest's expectation syntax.

Watch your Laravel app for unwanted changes when working with third-party packages.
Watch your Laravel app for unwanted changes when working with third-party packages.

Project Secure This package installs a Composer plugin that reports unwanted changes to your Laravel project code after installing or updating a third

A PHPStan package that supports working with Extbase

PHPStan for Extbase This package provides a couple of stubs and services to make your life easier when working with PHPStan and Extbase. Examples clas

Extend Laravel PHP framework to make working with Aiven databases simpler

Aiven Commands for Laravel ✨ Add some Aiven magic to your Laravel project ✨ This Laravel package provides some aiven commands for artisan to help with

Server-side library for working with Expo using PHP

expo-server-sdk-php Server-side library for working with Expo using PHP. If you have any problems with the code in this repository, feel free to open

A simple package for working with money.

Money A simple package for working with money. Main features: Simple API Livewire integration Custom currency support Highly customizable formatting R

An improved helper for working with cache

Laravel Cache Installation To get the latest version of Laravel Cache, simply require the project using Composer: $ composer require dragon-code/larav

A collection of useful traits for working with PHP 8.1 Enums

A library of helper traits for working with PHP 8.1 enums This package provides a series of traits that allows you to: RestorableFromName Trait Create

Comments
  • normalizeInterval should be improved

    normalizeInterval should be improved

    https://github.com/jeromegamez/duration-php/blob/67abef88a064f6b79a02fd769d618b99df34b5d7/src/Duration.php#L149

    This method should be improved to guard against DST and other timezone shenanigans...

            $now = new DateTimeImmutable();
            $then = $now->add($value);
            return $now->diff($then);
    

    should be

            $now = new DateTimeImmutable('@'.time());
            $then = $now->add($value);
            return $now->diff($then);
    

    this way your reference DateTimeImmutable object is created against a timestamp (aka) GMT which is not affected by Timezone trickery 😉 .

    Maybe refactor your code to always use this code everywhere instead of repeating it everywhere it would make the code more maintainable too. If I'm correct this pattern is used in many places currently.

    PS: if you are lazy .. you could even use DateTimeImmutable('@0') as a private static variable 👍 anyway this part should be improved.

    opened by nyamsprod 2
  • Update phpunit/phpunit requirement from ^7.0 to ^8.0

    Update phpunit/phpunit requirement from ^7.0 to ^8.0

    Updates the requirements on phpunit/phpunit to permit the latest version.

    Changelog

    Sourced from phpunit/phpunit's changelog.

    8.0.0 - 2019-02-01

    Changed

    • Implemented #3060: Cleanup PHPUnit\Framework\Constraint\Constraint
    • Implemented #3133: Enable dependency resolution by default
    • Implemented #3236: Define which parts of PHPUnit are covered by the backward compatibility promise
    • Implemented #3244: Enable result cache by default
    • Implemented #3288: The void_return fixer of php-cs-fixer is now in effect
    • Implemented #3439: Improve colorization of TestDox output
    • Implemented #3444: Consider data provider that provides data with duplicate keys to be invalid
    • Implemented #3467: Code location hints for [**requires**](https://github.com/requires) annotations as well as --SKIPIF--, --EXPECT--, --EXPECTF--, --EXPECTREGEX--, and --{SECTION}_EXTERNAL-- sections of PHPT tests
    • Implemented #3481: Improved --help output

    Deprecated

    • Implemented #3332: Deprecate annotation(s) for expecting exceptions
    • Implemented #3338: Deprecate assertions (and helper methods) that operate on (non-public) attributes
    • Implemented #3341: Deprecate optional parameters of assertEquals() and assertNotEquals()
    • Implemented #3369: Deprecate assertInternalType() and assertNotInternalType()
    • Implemented #3388: Deprecate the TestListener interface
    • Implemented #3425: Deprecate optional parameters of assertContains() and assertNotContains() as well as using these methods with string haystacks
    • Implemented #3494: Deprecate assertArraySubset()

    Removed

    • Implemented #2762: Drop support for PHP 7.1
    • Implemented #3123: Remove PHPUnit_Framework_MockObject_MockObject
    Commits

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Note: This repo was added to Dependabot recently, so you'll receive a maximum of 5 PRs for your first few update runs. Once an update run creates fewer than 5 PRs we'll remove that limit.

    You can always request more updates by clicking Bump now in your Dependabot dashboard.

    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot ignore this [patch|minor|major] version will close this PR and stop Dependabot creating any more for this minor/major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language
    • @dependabot badge me will comment on this PR with code to add a "Dependabot enabled" badge to your readme

    Additionally, you can set the following in your Dependabot dashboard:

    • Update frequency (including time of day and day of week)
    • Automerge options (never/patch/minor, and dev/runtime dependencies)
    • Pull request limits (per update run and/or open at any time)
    • Out-of-range updates (receive only lockfile updates, if desired)
    • Security updates (receive only security updates, if desired)

    Finally, you can contact us by mentioning @dependabot.

    dependencies 
    opened by dependabot-preview[bot] 1
Releases(4.3)
Owner
Jérôme Gamez
French name, German accent.
Jérôme Gamez
Wordpress Plugin to show a small amount of events in an easy to use calender/schedule

Wordpress Plugin to show a small amount of events in an easy to use calender/schedule

Michael Burtscher 32 Feb 7, 2022
Very easy to use PDO MYSQL API. Just Include in PHP file and get it working.

CRUD-MYSQL-API Very easy to use PDO MYSQL API. Just Include in PHP file and get it working. INSTALATION Step 1: git clone https://github.com/arhex-lab

Abdul Raheem 4 Jun 14, 2022
A simple PHP API to make working with SharePoint lists easy.

PHP SharePoint Lists API The PHP SharePoint Lists API is designed to make working with SharePoint Lists in PHP a less painful developer experience. Ra

Carl Saggs 170 Dec 10, 2022
Laravel-FCM is an easy to use package working with both Laravel and Lumen for sending push notification with Firebase Cloud Messaging (FCM).

Laravel-FCM Introduction Laravel-FCM is an easy to use package working with both Laravel and Lumen for sending push notification with Firebase Cloud M

Rahul Thapa 2 Oct 16, 2022
🐍 Web application made in PHP with Laravel where you can interact via API with my Snake game which is made in Python

Snake web application Project of the web application where you can interact via API with Snake game which is available to download on it. Application

Maciek Iwaniuk 1 Nov 26, 2022
CSV data manipulation made easy in PHP

CSV Csv is a simple library to ease CSV parsing, writing and filtering in PHP. The goal of the library is to be powerful while remaining lightweight,

The League of Extraordinary Packages 3k Jan 4, 2023
PHP Regular expressions made easy

PHPVerbalExpressions ported from VerbalExpressions VerbalExpressions is a PHP library that helps to construct hard regular expressions. Installation T

null 2.4k Jan 3, 2023
PHP Regular expressions made easy

PHPVerbalExpressions ported from VerbalExpressions VerbalExpressions is a PHP library that helps to construct hard regular expressions. Installation T

null 2.4k Dec 18, 2022
CSV data manipulation made easy in PHP

CSV Csv is a simple library to ease CSV parsing, writing and filtering in PHP. The goal of the library is to be powerful while remaining lightweight,

The League of Extraordinary Packages 3k Jan 1, 2023
Economy made easy for Minecraft: Bedrock

BedrockEconomy Economy made easy for Minecraft Bedrock Commands Name Description Usage Permission balance Show your and others balance balance [player

null 33 Oct 24, 2022