PHPackages                             mcustiel/mockable-datetime - 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. [Testing &amp; Quality](/categories/testing)
4. /
5. mcustiel/mockable-datetime

ActiveLibrary[Testing &amp; Quality](/categories/testing)

mcustiel/mockable-datetime
==========================

A DateTime library that allows mock dates and times in UnitTests.

v2.0.0(7y ago)5566.3k↑116.1%1GPL-3.0+PHPPHP &gt;=5.3

Since May 25Pushed 7y ago1 watchersCompare

[ Source](https://github.com/mcustiel/mockable-datetime)[ Packagist](https://packagist.org/packages/mcustiel/mockable-datetime)[ RSS](/packages/mcustiel-mockable-datetime/feed)WikiDiscussions master Synced 2w ago

READMEChangelog (5)Dependencies (1)Versions (8)Used By (1)

Mockable DateTime
=================

[](#mockable-datetime)

What is it
----------

[](#what-is-it)

Mockable DateTime is a library written in PHP that allows developers to mock the dates for unit tests. There are sometimes in which you need to verify that an action was executed with certain parameters, and one of them is a date or a time (generally obtained with date() or time() built-in functions) and is very difficult to ensure it will have a certain value at the time of the verification. Mockable DateTime solves this problem by giving the developer a way to obtain PHP's built-in DateTime class in a way, that the value it returns can be mocked from unit tests without the need of injecting DateTime as a dependency.

[![Build Status](https://camo.githubusercontent.com/b41c76ef6af0f91c17f23f1aac5acbb34722e1adc625bd9480432f10362929a7/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6d6375737469656c2f6d6f636b61626c652d6461746574696d652f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/mcustiel/mockable-datetime/build-status/master) [![Scrutinizer Code Quality](https://camo.githubusercontent.com/6965c4a84588ac2f074a4e264919df8c64fe1309d8aeaff2e98aa38f5e28c5cb/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6d6375737469656c2f6d6f636b61626c652d6461746574696d652f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/mcustiel/mockable-datetime/?branch=master) [![Code Coverage](https://camo.githubusercontent.com/7f2f7ddb09f9b10a2891100f349b79cd15d1cbc8f74442146d5a2da4f4e0f9bf/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6d6375737469656c2f6d6f636b61626c652d6461746574696d652f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/mcustiel/mockable-datetime/?branch=master)

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

[](#installation)

#### Composer:

[](#composer)

```
{
    "require": {
        "mcustiel/mockable-datetime": "^2.0"
    }
}
```

How to use it?
--------------

[](#how-to-use-it)

### In your code

[](#in-your-code)

Everytime you need to get system's date just use Mockable DateTime:

```
use Mcustiel\Mockable\DateTime;

// ...
function savePersonInfoInDatabase(Person $person)
{
    /** @var PersonDbEntity $person */
    $person = $this->converter->convert($person, PersonDbEntity::class);
    $person->setCreatedAt(DateTime::newPhpDateTime()); // DateTime::newImmutablePhpDateTime() can also be used
    $this->dbClient->insert($person);
}
// ...
```

Also arguments can be passed to create the DateTime object:

```
use Mcustiel\Mockable\DateTime;

// ...
function savePersonInfoInDatabase(Person $person)
{
    /** @var PersonDbEntity $person */
    $person = $this->converter->convert($person, PersonDbEntity::class);
    $person->setCreatedAt(DateTime::newPhpDateTime(
        '-4 months',
        new \DateTimeZone('America/New_York')
    )); // DateTime::newImmutablePhpDateTime() can also be used
    $this->dbClient->insert($person);
}
// ...
```

As you can see in the example, I'm not using PHP's \\DateTime directly. Instead I use Mockable DateTime to create instances of PHP's \\DateTime.

Then you have to test this, and assert that insert method was called with some specific date as an argument. For the example I'll use PHPUnit.

```
use Mcustiel\Mockable\DateTime;

// ...

/**
 * @test
 */
function shouldCallInsertPersonWithCorrectData()
{
    DateTime::setFixed(new \DateTime('2000-01-01 00:00:01'));
    // Now every call to MockableDateTime::newPhpDateTime() will always return "2000-01-01 00:00:01"
    /** @var Person $person */
    $person = new Person('John', 'Doe');
    /** @var PersonDbEntity $expected */
    $expected = new PersonDbEntity('John', 'Doe');
    $expected->setCreatedAt(new \DateTime('2000-01-01 00:00:01'));

    $this->dbClientMock->expects($this->once())
        ->method('insert')
        ->with($this->equalTo($expected));
    // ...and other needed mocks
    $this->unitUnderTest->savePersonInfoInDatabase($person);
}
// ...
```

That's it. For it to work the code and tests should be executed in the same environment (it won't work if you execute tests again a running instance of your webservice), but it should be enough for unit and some low level functional tests.

### DateTime methods:

[](#datetime-methods)

##### void setFixed(\\DateTime $dateTime)

[](#void-setfixeddatetime-datetime)

This method makes all instances of Mockable DateTime to always return the date and time specified by the $dateTime parameter.

##### void setOffset(\\DateTime $dateTime)

[](#void-setoffsetdatetime-datetime)

This method makes all instances of Mockable DateTime to always return a date and time with offset equal to the specified by the $dateTime parameter. The time starts to run from the moment of the call to this method. So if you set an offset equal to '2005-05-05 01:00:00' and sleep for 5 seconds, a new call to create a \\DateTime will return one with '2005-05-05 01:00:05' set.

##### void setSystem()

[](#void-setsystem)

This method makes all instances of Mockable DateTime to always return current system time (default behaviour).

##### \\DateTime newPhpDateTime($time = 'now', \\DateTimeZone $timeZone = null)

[](#datetime-newphpdatetimetime--now-datetimezone-timezone--null)

Creates a new instance of PHP's \\DateTime class based in the config of Mockable DateTime.

##### \\DateTimeImmutable newImmutablePhpDateTime($time = 'now', \\DateTimeZone $timeZone = null)

[](#datetimeimmutable-newimmutablephpdatetimetime--now-datetimezone-timezone--null)

Creates a new instance of PHP's \\DateTimeImmutable class based in the config of Mockable DateTime.

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity39

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity63

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

Total

5

Last Release

2630d ago

Major Versions

v1.1.2 → v2.0.02019-04-10

### Community

Maintainers

![](https://www.gravatar.com/avatar/8d9b3ff93206038debfa1f16a11bbfc10fca9b2f4ddfdafa00e27365d290cf0d?d=identicon)[mcustiel](/maintainers/mcustiel)

---

Top Contributors

[![mcustiel](https://avatars.githubusercontent.com/u/3268370?v=4)](https://github.com/mcustiel "mcustiel (28 commits)")

---

Tags

libraryteststimedatemocks

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mcustiel-mockable-datetime/health.svg)

```
[![Health](https://phpackages.com/badges/mcustiel-mockable-datetime/health.svg)](https://phpackages.com/packages/mcustiel-mockable-datetime)
```

###  Alternatives

[mockery/mockery

Mockery is a simple yet flexible PHP mock object framework

10.7k516.1M26.1k](/packages/mockery-mockery)[phpspec/phpspec

Specification-oriented BDD framework for PHP 7.1+

1.9k37.2M3.2k](/packages/phpspec-phpspec)[dealerdirect/phpcodesniffer-composer-installer

PHP\_CodeSniffer Standards Composer Installer Plugin

598170.6M2.2k](/packages/dealerdirect-phpcodesniffer-composer-installer)[dama/doctrine-test-bundle

Symfony bundle to isolate doctrine database tests and improve test performance

1.2k39.5M199](/packages/dama-doctrine-test-bundle)[thedoctor0/laravel-factory-generator

Automatically generate Laravel factories for your models.

2131.0M1](/packages/thedoctor0-laravel-factory-generator)[typo3/testing-framework

The TYPO3 testing framework provides base classes for unit and functional testing.

675.3M1.1k](/packages/typo3-testing-framework)

PHPackages © 2026

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