PHP code example of jc-it / yii2-datetime-behavior

1. Go to this page and download the library: Download jc-it/yii2-datetime-behavior 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/ */

    

jc-it / yii2-datetime-behavior example snippets


/**
 * @return array
 */
public function behaviors(): array
{
    return ArrayHelper::merge(
        parent::behaviors(),
        [
            DateTimeBehavior::class => [
                'class' => DateTimeBehavior::class
            ],
        ]
    );
}

/**
 * @return array
 */
public function behaviors(): array
{
    return ArrayHelper::merge(
        parent::behaviors(),
        [
            DateTimeBehavior::class => [
                'class' => DateTimeBehavior::class,
                'attributes' => [ // Map of attribute to type.
                    'date_attribute' => DateTimeBehavior::TYPE_DATE,
                    'datetime_attribute' => DateTimeBehavior::TYPE_DATETIME,
                    'time_attribute' => DateTimeBehavior::TYPE_TIME,
                ],
                'attributeSuffix' => 'Object', // Suffix that will be used to detect if the behavior must be triggered.
                'attributeTimezone' => 'UTC', //When storing datetime values in timestamp fields this should default timezone of your database.
                'dateTimeClass' => Carbon::class, //The class of the datetime objects to be returned. Must extend from Carbon.
            ],
        ]
    );
}

// Event has attribute from and until which are timestamps in the database
// Assuming in timezone Europe/Amsterdam

$event = Event::find()->one();
var_dump($event->from);
var_dump($event->fromObject);

// Will output

string '2019-01-01 12:00:00' (length=19)

object(Carbon\Carbon)
  public 'date' => string '2019-01-01 13:00:00.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Amsterdam' (length=16)