-
Notifications
You must be signed in to change notification settings - Fork 5
/
DateTimeBehavior.php
41 lines (35 loc) · 947 Bytes
/
DateTimeBehavior.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
namespace developeruz\behaviors;
/**
* DateTimeBehavior for Yii2
*
* @author Elle <elleuz@gmail.com>
* @version 0.1
* @package Behaviors for Yii2
*
*/
use yii\behaviors\AttributeBehavior;
use yii\db\ActiveRecord;
class DateTimeBehavior extends AttributeBehavior
{
public $dateTimeFields;
public $format = 'd-m-Y H:i:s';
public function events()
{
return [
ActiveRecord::EVENT_AFTER_FIND => 'convertDate',
ActiveRecord::EVENT_BEFORE_VALIDATE => 'convertDateToDB',
];
}
public function convertDate()
{
$this->owner->{$this->dateTimeFields} = date($this->format, strtotime($this->owner->{$this->dateTimeFields}));
}
public function convertDateToDB()
{
$this->owner->{$this->dateTimeFields} = date_create_from_format(
$this->format,
$this->owner->{$this->dateTimeFields}
)->format('Y-m-d H:i:s');
}
}