Skip to content

Xử lý thời gian

1. Định dạng thời gian tiêu chuẩn

  • Sử dụng ISO8601 cho cả Frontend và Backend khi truyền dữ liệu
  • Ví dụ: 2025-05-02T15:30:00+07:00

2. Đăng ký CarbonImmutable toàn cục

php
<?php

declare(strict_types=1);

namespace App\Providers;

use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\ServiceProvider;

final class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Date::use(CarbonImmutable::class);
    }
}

3. Type Hinting cho tham số thời gian

  • Sử dụng CarbonInterface khi cần API tiện ích của Carbon
  • Sử dụng DateTimeInterface cho các trường hợp đơn giản
php
<?php

declare(strict_types=1);

namespace App\Services;

use Carbon\CarbonInterface;
use DateTimeInterface;

final class TimeService
{
    public function handleViaCarbon(CarbonInterface $when): void
    {
        // …
    }

    public function logCreatedAt(DateTimeInterface $timestamp): void
    {
        // …
    }
}

4. Lý do sử dụng CarbonImmutable

Vấn đề khi dùng Carbon (mutable)CarbonImmutable khắc phục
$dt->addDay() thay đổi $dt gốcPhương thức trả về instance mới
Side-effect khó debugTính bất biến, dễ dự đoán
setTimezone() ảnh hưởng toàn cụcKhông có side-effect
php
$expiresAt = Carbon::now();
cache(['key' => 'value'], $expiresAt->addMinutes(5)); // $expiresAt bị thay đổi!
doSomething($expiresAt);                              // thời gian sai

$expiresAt = CarbonImmutable::now();
cache(['key' => 'value'], $expiresAt->addMinutes(5)); // $expiresAt giữ nguyên
doSomething($expiresAt);                              // chính xác

5. Casting trong Eloquent Model

php
<?php

declare(strict_types=1);

namespace App\Models;

use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Model;

/**
 * @property CarbonImmutable          $created_at
 * @property CarbonImmutable          $updated_at
 * @property CarbonImmutable|null     $delivery_date
 * @property CarbonImmutable|null     $start_time
 * @property CarbonImmutable|null     $end_time
 */
final class Order extends Model
{
    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'created_at'    => 'immutable_datetime',
            'updated_at'    => 'immutable_datetime',
            'delivery_date' => 'immutable_datetime',
            'start_time'    => 'immutable_datetime',
            'end_time'      => 'immutable_datetime',
        ];
    }
}

Lưu ý

  • Sử dụng cast immutable_datetime (Laravel 10+)
  • Thêm PHPDoc để IDE và PHPStan kiểm tra chính xác