PHPackages                             nedarta/yii2-datetime-behavior - 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. nedarta/yii2-datetime-behavior

ActiveYii2-extension[Utility &amp; Helpers](/categories/utility)

nedarta/yii2-datetime-behavior
==============================

Timezone-aware datetime behavior for Yii2

v0.1.0(3mo ago)110MITPHPPHP &gt;=8.1

Since Feb 4Pushed 3mo agoCompare

[ Source](https://github.com/nedarta/yii2-datetime-behavior)[ Packagist](https://packagist.org/packages/nedarta/yii2-datetime-behavior)[ RSS](/packages/nedarta-yii2-datetime-behavior/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

nedarta/yii2-datetime-behavior
==============================

[](#nedartayii2-datetime-behavior)

Timezone-aware DateTime behavior for Yii2 ActiveRecord models.

This extension provides a clean, future-proof way to automatically convert datetime values between **database format** and **user-facing format**, while keeping your database consistent (UTC / UNIX) and your UI localized.

---

Features
--------

[](#features)

- Automatic timezone conversion (UI ↔ DB)
- Works on `afterFind` and `beforeSave`
- Supports **UNIX timestamps** and **DATETIME** columns
- **Timezone offset inclusion** for robust Formatter integration
- Includes `toTimestamp()` helper for UTC-normalized timestamps
- Multiple attributes per model
- Ready for multi-timezone users
- Easy to test, no UI or widget coupling
- Compatible with Yii2 Formatter (`asDateTime()`)

---

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

[](#installation)

```
composer require nedarta/yii2-datetime-behavior
```

---

Basic Usage
-----------

[](#basic-usage)

### Model configuration

[](#model-configuration)

```
use nedarta\behaviors\DateTimeBehavior;

class Post extends \yii\db\ActiveRecord
{
    public function behaviors(): array
    {
        return [
            [
                'class' => DateTimeBehavior::class,
                'attributes' => ['created_at', 'scheduled_at'],
                'inputFormat' => 'Y-m-d H:i',
                // Optional:
                // 'dbFormat' => 'unix',          // default: 'unix'
                // 'serverTimeZone' => 'UTC',     // default: 'UTC'
                // 'displayTimeZone' => null,     // default: null (falls back to Yii::$app->timeZone)
            ],
        ];
    }
}
```

---

What Happens Automatically
--------------------------

[](#what-happens-automatically)

StepValueDescriptionDatabase value`1704031200`UTC Unix TimestampAfter `find()``2023-12-31 16:00 +02:00`Local time with offsetUser edits`2024-01-01 10:00`UI Form input (no offset)Before `save()``1704103200`Converted back to UTCThe database always stays in **UTC / UNIX** format.
The model attribute always contains a **user-facing value**.

---

Configuration Options
---------------------

[](#configuration-options)

OptionTypeDefaultDescription`attributes``array``[]`Attributes to convert`dbFormat``string``unix``unix`, `datetime`, `date`, `time`, or custom PHP format string (e.g. `Y-m-d`)`inputFormat``string``Y-m-d H:i`User / UI format`serverTimeZone``string``UTC`Database timezone (usually UTC)`displayTimeZone``stringnull``null`---

How It Works
------------

[](#how-it-works)

### DB → UI (`afterFind`)

[](#db--ui-afterfind)

1. Reads value from database
2. Interprets it using `serverTimeZone`
3. Converts to `displayTimeZone`
4. Formats as `inputFormat` + `P` (timezone offset)

### UI → DB (`beforeSave`)

[](#ui--db-beforesave)

1. Parses user input using `inputFormat` (tries both with and without offset)
2. Interprets it in `displayTimeZone` (unless offset provided)
3. Converts to `serverTimeZone`
4. Stores as UNIX timestamp or DATETIME string

---

### Automatic Timezone Fallback

[](#automatic-timezone-fallback)

If you don't explicitly set `displayTimeZone` in the behavior, it will automatically pick up your application's timezone from `Yii::$app->formatter->timeZone` or `Yii::$app->timeZone`. This ensures consistency across your application without extra configuration.

```
// In common/config/main.php
'timeZone' => 'Asia/Tokyo',

// In your Model - no displayTimeZone needed!
[
    'class' => DateTimeBehavior::class,
    'attributes' => ['created_at'],
],
```

---

Helper Methods
--------------

[](#helper-methods)

### `toTimestamp($attribute)`

[](#totimestampattribute)

Returns a UTC-normalized UNIX timestamp for a given attribute, regardless of whether the attribute currently holds a raw database value or a localized UI string.

```
$timestamp = $model->getBehavior('dt')->toTimestamp('created_at');
```

---

Querying
--------

[](#querying)

When querying the database (e.g., filtering for "today's events"), you must compare against UTC time. You can use the `toDbValue()` helper to correctly format your filter values.

### Option 1: Static Helper (Simplest)

[](#option-1-static-helper-simplest)

You don't need a model instance, just the class name:

```
use nedarta\behaviors\DateTimeBehavior;

$now = DateTimeBehavior::now(Event::class);
$query->andWhere(['>=', 'datetime', $now]);
```

### Option 2: Direct Model Call

[](#option-2-direct-model-call)

If you have a model instance, you can call the behavior methods directly on it:

```
$model = new Event();
$query->andWhere(['>=', 'datetime', $model->toDbValue('now')]);
```

Alternatively, if you are using `unix` timestamps, you can simply use the PHP `time()` function:

```
// Only for dbFormat => 'unix'
$query->andWhere(['>=', 'datetime', time()]);
```

---

Batch Operations
----------------

[](#batch-operations)

Since `ActiveRecord::updateAll()` and `insertAll()` do not trigger model behaviors, you can use the `normalize()` method to convert your data array before passing it to the database:

```
$model = new Post();
$dt = $model->getBehavior('dt');

// Normalize UI-formatted data for batch update
$data = $dt->normalize([
    'status' => Post::STATUS_PUBLISHED,
    'published_at' => '2024-01-01 12:00', // Will be converted to UTC/Unix
]);

Post::updateAll($data, ['author_id' => 1]);
```

---

What This Extension Does NOT Do
-------------------------------

[](#what-this-extension-does-not-do)

- Render form inputs or widgets
- Depend on Tempus Dominus or any UI library
- Store business logic
- Guess or auto-detect timezones

This extension operates strictly at the **model layer**.

---

Recommended Architecture
------------------------

[](#recommended-architecture)

```
[ UI / Widget ]
       ↓
[ ActiveRecord Attribute ]
       ↓
[ DateTimeBehavior ]
       ↓
[ Database (UTC / UNIX) ]

```

---

Requirements
------------

[](#requirements)

- PHP 8.1+
- Yii2 `^2.0`

---

---

Testing
-------

[](#testing)

Run the test suite via Composer:

```
composer test
```

---

License
-------

[](#license)

MIT

---

Roadmap
-------

[](#roadmap)

- PHPUnit test suite
- Support for additional database formats (date, time, custom)
- Support for batch operations (e.g. `updateAll()`)
- Query helper `toDbValue()` for correct filtering
- Read-only / write-only modes
- Integration with popular date/time widgets

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance82

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity32

Early-stage or recently created project

 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

Unknown

Total

1

Last Release

95d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5b419e3f062d93e558b33278c937dacbb5367edf84b8d8b134ba1d86d56f185b?d=identicon)[nedarta](/maintainers/nedarta)

---

Top Contributors

[![nedarta](https://avatars.githubusercontent.com/u/16962105?v=4)](https://github.com/nedarta "nedarta (24 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/nedarta-yii2-datetime-behavior/health.svg)

```
[![Health](https://phpackages.com/badges/nedarta-yii2-datetime-behavior/health.svg)](https://phpackages.com/packages/nedarta-yii2-datetime-behavior)
```

###  Alternatives

[dmstr/yii2-cookie-consent

Yii2 Cookie Consent Widget

1452.6k](/packages/dmstr-yii2-cookie-consent)

PHPackages © 2026

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