nedarta/yii2-local-datetime-behavior

Yii2 behavior for converting local datetime input to UTC timestamp and back

Installs: 1

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

Type:yii2-extension

pkg:composer/nedarta/yii2-local-datetime-behavior

1.0.0 2025-12-19 13:52 UTC

This package is auto-updated.

Last update: 2025-12-19 13:57:18 UTC


README

Yii2 behavior for converting local datetime strings (for example from Tempus Dominus) into UTC Unix timestamps for database storage, and converting them back to local time for display in forms and views.

This behavior is designed to eliminate timezone-related bugs (+1h / +2h, DST issues) by enforcing a clear and predictable datetime flow.

Features

  • Stores datetime values as UTC Unix timestamps in the database
  • Works with local datetime inputs (no timezone attached)
  • Handles Daylight Saving Time (DST) correctly
  • No usage of strtotime()
  • Compatible with:
    • Tempus Dominus
    • Flatpickr
    • HTML5 datetime-local
  • Clean, reusable Yii2 behavior

Installation

Install via Composer:

composer require nedarta/yii2-local-datetime-behavior

Usage

Attach the behavior to your ActiveRecord model:

use nedarta\behaviors\LocalDatetimeBehavior;

public function behaviors(): array
{
    return [
        [
            'class' => LocalDatetimeBehavior::class,
            'attribute' => 'datetime',
            'format' => 'Y-m-d H:i',
            'timezone' => 'Europe/Riga',
        ],
    ];
}

Configuration Options

Option Type Default Description
attribute string datetime Model attribute storing the timestamp
format string Y-m-d H:i Datetime format used in forms
timezone string Europe/Riga Local/UI timezone

Example Flow

User Input (Form)

2025-12-20 20:00

Database Value (UTC)

1766246400

Displayed Output

2025-12-20 20:00

How It Works

  • beforeSave
    • Converts local datetime string into UTC Unix timestamp
  • afterFind
    • Converts UTC timestamp back into local datetime string

All timezone logic is centralized in one place.

Best Practices

  • Store only UTC timestamps in the database
  • Let UI components work in local time
  • Never use strtotime() for user input
  • Keep timezone conversion out of controllers and views

License

MIT