PHP code example of emilienkopp / formats-dates-trait

1. Go to this page and download the library: Download emilienkopp/formats-dates-trait library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

emilienkopp / formats-dates-trait example snippets


use EmilienKopp\DatesFormatter\FormatsDates;

class User extends Model
{
    use FormatsDates;

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

// 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)

// 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

// 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();

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