PHPackages                             emilienkopp/formats-dates-trait - 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. emilienkopp/formats-dates-trait

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

emilienkopp/formats-dates-trait
===============================

A Laravel-Carbon trait for easy date formatting

v1.0.5(9mo ago)0154MITPHPPHP ^8.2CI passing

Since Nov 13Pushed 9mo ago1 watchersCompare

[ Source](https://github.com/EmilienKopp/FormatsDates)[ Packagist](https://packagist.org/packages/emilienkopp/formats-dates-trait)[ RSS](/packages/emilienkopp-formats-dates-trait/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (5)Versions (7)Used By (0)

Laravel Dates Formatter Trait
=============================

[](#laravel-dates-formatter-trait)

[![Latest Version on Packagist](https://camo.githubusercontent.com/d34e8ffd341a123eaacf81a53c6c7800375ded2d2eeab3b7094ccdf6862d2b6f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f656d696c69656e6b6f70702f666f726d6174732d64617465732d74726169742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/emilienkopp/formats-dates-trait)[![Total Downloads](https://camo.githubusercontent.com/e14e4c75e92a032e0f7ad0275c7b33753fd3a8769cb57e5f81ad8939619f356b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f656d696c69656e6b6f70702f666f726d6174732d64617465732d74726169742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/emilienkopp/formats-dates-trait)[![License](https://camo.githubusercontent.com/fe212639288d314603d8f7169c7c67e75e3edd3036264926cbc602968f8c12e8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f656d696c69656e6b6f70702f666f726d6174732d64617465732d74726169743f7374796c653d666c61742d737175617265)](LICENSE.md)

A Laravel trait that provides elegant date formatting capabilities to your models with automatic format detection and magic method support.

Features
--------

[](#features)

- 🔄 Automatic format detection based on property names and types
- ✨ Magic method support for cleaner syntax
- 🔍 Reflection-based property access
- 🛡️ Null-safe operations
- 🎨 Customizable date formats
- 🎯 Type-hint aware

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

[](#installation)

You can install the package via composer:

```
composer require emilienkopp/formats-dates-trait
```

Usage
-----

[](#usage)

Add the trait to your model:

```
use EmilienKopp\DatesFormatter\FormatsDates;

class User extends Model
{
    use FormatsDates;

    protected $dates = [
        'created_at',
        'updated_at',
        'birth_date',
        'login_time'
    ];
}
```

Now you can use 'getFormattedDate' method or magic methods to format your dates.

⚠️ Note: magic methods are `camelCase` versions of the property names.

### Automatic Format Detection

[](#automatic-format-detection)

The trait automatically determines the appropriate format based on property names and types. It uses strict suffix matching to avoid false positives.

#### Format Detection Rules (in order of precedence)

[](#format-detection-rules-in-order-of-precedence)

1. **Type hints**

    - Properties typed as `DateTime` → Uses datetime format
2. **Property name suffixes**

    - Ends with `_datetime` or `_at` → Uses datetime format
    - Ends with `_time` → Uses time format
    - Ends with `_date` → Uses date format
    - All others → Uses default date format

Magic methods are generated based on the suffixes. Therefore, any property that does not follow the suffix rules will not have a magic method invoked and will likely throw a `BadMethodCallException`.

#### Examples

[](#examples)

```
// DateTime format (Y-m-d H:i:s)
created_at          ✓
updated_at          ✓
deleted_datetime    ✓
attestation         ✗ (no underscored suffix)
updater_name        ✗ (not a supported suffix)

// Time format (H:i:s)
login_time          ✓
start_time          ✓
datetime_time       ✓
overtime            ✗ (no underscore prefix)

// Date format (Y-m-d)
birth_date          ✓
publish_date        ✓
mandated_by         ✗ (not a supported suffix)
validate            ✗ (no underscore prefix)
```

### Basic Usage

[](#basic-usage)

```
// Using magic methods
$user->createdAt();        // Returns '2024-03-13'
$user->updatedAt();        // Returns '2024-03-13'
$user->loginTime();        // Returns '14:30:00'

// Using custom formats
$user->createdAt('d/m/Y'); // Returns '13/03/2024'
$user->loginTime('H:i');   // Returns '14:30'

// Using the direct method
$user->getFormattedDate('created_at');           // Uses auto-detected format
$user->getFormattedDate('created_at', 'd/m/Y');  // Uses custom format
```

### Customizing Default Formats

[](#customizing-default-formats)

You can customize the default formats for your model:

```
// Customize date format
User::setDefaultDateFormat('d/m/Y');

// Customize datetime format
User::setDefaultDatetimeFormat('d/m/Y H:i');

// Customize time format
User::setDefaultTimeFormat('H:i');

// Get current formats
$dateFormat = User::getDefaultDateFormat();
$datetimeFormat = User::getDefaultDatetimeFormat();
```

⚠️ Note: Format changes are applied per model class, not globally.

### Null Safety

[](#null-safety)

The trait handles null values gracefully:

```
$user->birth_date = null;
$user->birthDate(); // Returns null
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

### Security

[](#security)

If you discover any security related issues, please contact me instead of using the issue tracker.

Support Laravel Versions
------------------------

[](#support-laravel-versions)

- Laravel 7.x through 11.x
- PHP 7.4 or higher

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance58

Moderate activity, may be stable

Popularity11

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

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

Recently: every ~67 days

Total

6

Last Release

275d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b9e77e55bb8341a1fa99f8348597070b4de230b5fc457e866e4f196dd56843f1?d=identicon)[EmilienKopp](/maintainers/EmilienKopp)

---

Top Contributors

[![EmilienKopp](https://avatars.githubusercontent.com/u/91975560?v=4)](https://github.com/EmilienKopp "EmilienKopp (17 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/emilienkopp-formats-dates-trait/health.svg)

```
[![Health](https://phpackages.com/badges/emilienkopp-formats-dates-trait/health.svg)](https://phpackages.com/packages/emilienkopp-formats-dates-trait)
```

###  Alternatives

[erlandmuchasaj/laravel-gzip

Gzip your responses.

40129.3k2](/packages/erlandmuchasaj-laravel-gzip)[interaction-design-foundation/laravel-geoip

Support for multiple Geographical Location services.

17221.0k3](/packages/interaction-design-foundation-laravel-geoip)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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