PHPackages                             joefallon/phptime - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. joefallon/phptime

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

joefallon/phptime
=================

This package contains a set of classes for making it easier to work with time in PHP.

v5.0.0(8mo ago)01471MITPHPPHP &gt;=7.4

Since Aug 29Pushed 8mo ago1 watchersCompare

[ Source](https://github.com/joefallon/phptime)[ Packagist](https://packagist.org/packages/joefallon/phptime)[ Docs](https://github.com/joefallon/phptime)[ RSS](/packages/joefallon-phptime/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (1)Versions (13)Used By (0)

phptime
=======

[](#phptime)

Lightweight, well-tested utilities for working with time in PHP — designed for simplicity, clarity, and testability. Useful when you need small, dependable helpers like a high-resolution chronograph, readable day/month enums, or MySQL-compatible timestamps.

This library favors explicit, testable APIs and minimal dependencies. It's not a full-featured date/time framework — instead, it provides pragmatic, focused tools that many PHP apps need.

- **Project:** [JoeFallon/phptime](https://github.com/JoeFallon/phptime)
- **License:** MIT
- **PHP Requirement:** 7.4+ (compatible with PHP 8.x)

Why Use This Library?
---------------------

[](#why-use-this-library)

- Small, focused utilities you can drop into any project
- Dependency-injection friendly for deterministic tests
- Includes a test suite (PHPUnit 9.6 compatible for PHP 7.4)
- Clear, well-documented API for common use-cases (timestamps, enums, timers)

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Quick Start](#quick-start)
- [API Reference](#api-reference)

    - [Chronograph](#chronograph)
    - [DaysEnum and MonthsEnum](#daysenum-and-monthsenum)
    - [MySqlDateTime](#mysqldatetime)
    - [Clock and DateTime Providers (Dependency Injection)](#clock-and-datetime-providers-dependency-injection)
- [Testing](#testing)
- [Contributing](#contributing)
- [Changelog &amp; Compatibility](#changelog--compatibility)
- [License](#license)

---

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

[](#installation)

Install via Composer (recommended):

```
composer require joefallon/phptime
```

If you're a library author, add it to your `composer.json` as a dependency and run:

```
composer install
composer update
```

---

Quick Start
-----------

[](#quick-start)

### Chronograph (Measure Elapsed Time)

[](#chronograph-measure-elapsed-time)

```
use JoeFallon\PhpTime\Chronograph;

$timer = new Chronograph();
$timer->start();
// ... work ...
$timer->stop();

echo $timer->getElapsedMilliseconds(); // e.g. 12.3
```

### MySQL DATETIME Strings

[](#mysql-datetime-strings)

```
use JoeFallon\PhpTime\MySqlDateTime;

$now = MySqlDateTime::nowTimestamp();
// e.g. "2025-10-13 14:05:33"
```

### Days and Months Enum Helpers

[](#days-and-months-enum-helpers)

```
use JoeFallon\PhpTime\DaysEnum;
use JoeFallon\PhpTime\MonthsEnum;

$days = DaysEnum::all();
$months = MonthsEnum::all();

if (MonthsEnum::isValid('Feb')) { /* ... */ }
```

---

API Reference
-------------

[](#api-reference)

### Chronograph

[](#chronograph)

**Namespace:** `JoeFallon\PhpTime\Chronograph`

A high-resolution timer for measuring elapsed time.

**Methods:**

- `start()` — start or restart the timer
- `stop()` — stop the timer (throws `LogicException` if not started)
- `reset()` — clear start and stop times
- `isRunning()` — check if timer is running
- `getElapsedSeconds()` — elapsed seconds (float)
- `getElapsedMilliseconds()` — elapsed milliseconds (float)

**Example with Dependency Injection:**

```
use JoeFallon\PhpTime\Chronograph;
use JoeFallon\PhpTime\SystemClock;

$clock = new SystemClock();
$chrono = new Chronograph($clock);
$chrono->start();
// ...
$chrono->stop();

echo $chrono->getElapsedMilliseconds();
```

---

### DaysEnum and MonthsEnum

[](#daysenum-and-monthsenum)

**Namespaces:** `JoeFallon\PhpTime\DaysEnum`, `JoeFallon\PhpTime\MonthsEnum`

Value-object style enums exposing full-name constants and short aliases (e.g., `MonthsEnum::JANUARY` and `MonthsEnum::JAN`) with helper methods:

- `all()` — returns all values
- `isValid($value)` — check if value is valid
- `indexOf($value)` — get index of value
- `fromIndex($index)` — get value from index

**Example:**

```
use JoeFallon\PhpTime\MonthsEnum;

$all = MonthsEnum::all();        // ['January', 'February', ...]
$index = MonthsEnum::indexOf('Mar'); // 2
$name = MonthsEnum::fromIndex(11);   // 'December'
```

---

### MySqlDateTime

[](#mysqldatetime)

**Namespace:** `JoeFallon\PhpTime\MySqlDateTime`

Utility for producing MySQL-ready DATETIME strings (`Y-m-d H:i:s`) with optional microseconds.

**Primary Static Methods:**

- `nowTimestamp(?DateTimeProviderInterface $provider = null): string` — current timestamp
- `nowTimestampWithMicroseconds(?DateTimeProviderInterface $provider = null): string` — timestamp with microseconds
- `nowUtcTimestamp(?DateTimeProviderInterface $provider = null, bool $withMicro = false)` — UTC timestamp
- `fromDateTime(DateTimeInterface $dt, bool $withMicro = false): string` — format any `DateTimeInterface`
- `fromTimestamp(int $seconds, int $microseconds = 0, bool $utc = false, bool $withMicro = false): string` — from epoch + microseconds
- `validate(string $value, bool $allowMicro = false): bool` — validate MySQL DATETIME string

**Example (Production):**

```
use JoeFallon\PhpTime\MySqlDateTime;

$now = MySqlDateTime::nowTimestamp();
// Insert into DB: created_at = $now
```

**Example (Testing with Deterministic Provider):**

```
use JoeFallon\PhpTime\MySqlDateTime;
use JoeFallon\PhpTime\DateTimeProviderInterface;
use DateTimeImmutable;
use DateTimeZone;

$provider = new class implements DateTimeProviderInterface {
    public function now(): \DateTimeInterface
    {
        return new DateTimeImmutable('2001-01-02 03:04:05', new DateTimeZone('UTC'));
    }
};

MySqlDateTime::nowTimestamp($provider); // '2001-01-02 03:04:05'
```

---

### Clock and DateTime Providers (Dependency Injection)

[](#clock-and-datetime-providers-dependency-injection)

For deterministic testing, the library provides interfaces and default system implementations:

- `ClockInterface` / `SystemClock` — used by `Chronograph` (returns float seconds)
- `DateTimeProviderInterface` / `SystemDateTimeProvider` — used by `MySqlDateTime` (returns `DateTimeInterface`)

Inject custom implementations (fake clocks, controlled time sources) for predictable behavior in tests.

---

Testing
-------

[](#testing)

The project includes a PHPUnit test suite. Run tests locally:

```
composer install
./vendor/bin/phpunit -c phpunit.xml.dist
```

> Windows users: `vendor\bin\phpunit -c phpunit.xml.dist`

---

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

[](#contributing)

Contributions are welcome. Suggested workflow:

1. Fork the repository
2. Create a feature branch
3. Add tests covering new or changed behavior
4. Run the test suite and ensure all tests pass
5. Open a pull request with a clear description

**Coding Guidelines:**

- Keep the API small and explicit
- Use dependency injection for clock/time providers to enable deterministic tests
- Add unit tests for new behavior and edge cases

---

Changelog &amp; Compatibility
-----------------------------

[](#changelog--compatibility)

- PHP 7.4+ supported
- PHPUnit 9.6 for PHP 7.4
- Test suite maintained for backward compatibility

---

License
-------

[](#license)

MIT License — see the `LICENSE` file for details

---

Support &amp; Contact
---------------------

[](#support--contact)

If you encounter bugs or want enhancements, open an issue on the project repository. The test suite contains usage examples and edge-case handling.

Enjoy, and thanks for using phptime! — Joe Fallon

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance59

Moderate activity, may be stable

Popularity11

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity70

Established project with proven stability

 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 ~406 days

Recently: every ~982 days

Total

11

Last Release

262d ago

Major Versions

v1.0.2 → v2.0.02014-10-26

v2.0.0 → v3.0.02014-10-28

v3.0.1 → v4.0.02015-01-10

v4.0.3 → v5.0.02025-10-13

PHP version history (2 changes)v1.0.0PHP &gt;=5.3.0

v5.0.0PHP &gt;=7.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/97cecfa80ffec8e9e7b5d0ff6df026b636e31a15fe0c2155baba402b5d4f0819?d=identicon)[joefallon](/maintainers/joefallon)

---

Top Contributors

[![joefallon](https://avatars.githubusercontent.com/u/4212989?v=4)](https://github.com/joefallon "joefallon (15 commits)")

---

Tags

phpdatatimechronograph

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/joefallon-phptime/health.svg)

```
[![Health](https://phpackages.com/badges/joefallon-phptime/health.svg)](https://phpackages.com/packages/joefallon-phptime)
```

###  Alternatives

[dater/dater

Compact PHP library for working with date/time in different formats &amp; timezones.

14484.2k](/packages/dater-dater)[zjkal/time-helper

一个简单快捷的PHP日期时间助手类库。 a smart PHP datetime helper library.

21031.2k2](/packages/zjkal-time-helper)[kirouane/interval

Library to handel intervals

2878.4k](/packages/kirouane-interval)[hi-folks/data-block

Data class for managing nested arrays and JSON data.

1462.9k](/packages/hi-folks-data-block)[iteks/laravel-enum

A comprehensive Laravel package providing enhanced enum functionalities, including attribute handling, select array conversions, and fluent facade interactions for robust enum management in Laravel applications.

2518.6k](/packages/iteks-laravel-enum)[maherelgamil/arabicdatetime

Easy and useful tool to generate arabic or hijri date with multi-language support for laravel

414.6k](/packages/maherelgamil-arabicdatetime)

PHPackages © 2026

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