# TimestampBehavior

> TimestampBehavior automatically fills the specified attributes with the current timestamp.

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [behaviors](/docs/api/yii/behaviors/index.md) › TimestampBehavior

| class | `yii\behaviors\TimestampBehavior` |
| --- | --- |
| Extends | [`AttributeBehavior`](/docs/api/yii/behaviors/attributebehavior/index.md) » [`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md) » [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| Implements | [`yii\base\Configurable`](/docs/api/yii/base/configurable/index.md) |
| Since | 2.0 |
| Source | [`framework/behaviors/TimestampBehavior.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/behaviors/TimestampBehavior.php#L76) |

TimestampBehavior automatically fills the specified attributes with the current timestamp.

To use TimestampBehavior, insert the following code to your ActiveRecord class:

```
use yii\behaviors\TimestampBehavior;

public function behaviors()
{
    return [
        TimestampBehavior::class,
    ];
}
```

By default, TimestampBehavior will fill the `created_at` and `updated_at` attributes with the current timestamp
when the associated AR object is being inserted; it will fill the `updated_at` attribute
with the timestamp when the AR object is being updated. The timestamp value is obtained by `time()`.

Because attribute values will be set automatically by this behavior, they are usually not user input and should therefore
not be validated, i.e. `created_at` and `updated_at` should not appear in the [rules()](/docs/api/yii/base/model/index.md#method-rules) method of the model.

For the above implementation to work with MySQL database, please declare the columns(`created_at`, `updated_at`) as int(11) for being UNIX timestamp.

If your attribute names are different or you want to use a different way of calculating the timestamp,
you may configure the [`$createdAtAttribute`](/docs/api/yii/behaviors/timestampbehavior/index.md#property-createdAtAttribute), [`$updatedAtAttribute`](/docs/api/yii/behaviors/timestampbehavior/index.md#property-updatedAtAttribute) and [`$value`](/docs/api/yii/behaviors/timestampbehavior/index.md#property-value) properties like the following:

```
use yii\db\Expression;

public function behaviors()
{
    return [
        [
            'class' => TimestampBehavior::class,
            'createdAtAttribute' => 'create_time',
            'updatedAtAttribute' => 'update_time',
            'value' => new Expression('NOW()'),
        ],
    ];
}
```

In case you use an [`Expression`](/docs/api/yii/db/expression/index.md) object as in the example above, the attribute will not hold the timestamp value, but
the Expression object itself after the record has been saved. If you need the value from DB afterwards you should call
the [refresh()](/docs/api/yii/db/activerecord/index.md#method-refresh) method of the record.

TimestampBehavior also provides a method named [`touch()`](/docs/api/yii/behaviors/timestampbehavior/index.md#method-touch) that allows you to assign the current
timestamp to the specified attribute(s) and save them to the database. For example,

```
$model->touch('creation_time');
```

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| <span id="property-attributes"></span>[`$attributes`](/docs/api/yii/behaviors/attributebehavior/index.md#property-attributes) | `array` | List of attributes that are to be automatically filled with the value specified via [`$value`](/docs/api/yii/behaviors/attributebehavior/index.md#property-value). Default: `[]`. | [`AttributeBehavior`](/docs/api/yii/behaviors/attributebehavior/index.md) |
| <span id="property-createdAtAttribute"></span>`$createdAtAttribute` | `string\|false` | The attribute that will receive timestamp value Set this property to false if you do not want to record the creation time. Default: `'created_at'`. | `TimestampBehavior` |
| <span id="property-owner"></span>[`$owner`](/docs/api/yii/base/behavior/index.md#property-owner) | `yii\base\T\|null` | The owner of this behavior Default: `null`. | [`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md) |
| <span id="property-preserveNonEmptyValues"></span>[`$preserveNonEmptyValues`](/docs/api/yii/behaviors/attributebehavior/index.md#property-preserveNonEmptyValues) | `bool` | Whether to preserve non-empty attribute values. Default: `false`. Available since 2.0.13. | [`AttributeBehavior`](/docs/api/yii/behaviors/attributebehavior/index.md) |
| <span id="property-skipUpdateOnClean"></span>[`$skipUpdateOnClean`](/docs/api/yii/behaviors/attributebehavior/index.md#property-skipUpdateOnClean) | `bool` | Whether to skip this behavior when the `$owner` has not been modified Default: `true`. Available since 2.0.8. | [`AttributeBehavior`](/docs/api/yii/behaviors/attributebehavior/index.md) |
| [`$updatedAtAttribute`](#property-updatedAtAttribute) | `string\|false` | The attribute that will receive timestamp value. Default: `'updated_at'`. | `TimestampBehavior` |
| [`$value`](#property-value) | `mixed` | Default: `null`. | `TimestampBehavior` |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| <span id="method-__construct"></span>[`__construct()`](/docs/api/yii/base/baseobject/index.md#method-__construct) | Constructor. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__call"></span>[`__call()`](/docs/api/yii/base/baseobject/index.md#method-__call) | Calls the named method which is not a class method. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__get"></span>[`__get()`](/docs/api/yii/base/baseobject/index.md#method-__get) | Returns the value of an object property. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__isset"></span>[`__isset()`](/docs/api/yii/base/baseobject/index.md#method-__isset) | Checks if a property is set, i.e. defined and not null. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__set"></span>[`__set()`](/docs/api/yii/base/baseobject/index.md#method-__set) | Sets value of an object property. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__unset"></span>[`__unset()`](/docs/api/yii/base/baseobject/index.md#method-__unset) | Sets an object property to null. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-attach"></span>[`attach()`](/docs/api/yii/base/behavior/index.md#method-attach) | Attaches the behavior object to the component. | [`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md) |
| <span id="method-canGetProperty"></span>[`canGetProperty()`](/docs/api/yii/base/baseobject/index.md#method-canGetProperty) | Returns a value indicating whether a property can be read. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-canSetProperty"></span>[`canSetProperty()`](/docs/api/yii/base/baseobject/index.md#method-canSetProperty) | Returns a value indicating whether a property can be set. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-className"></span>[`className()`](/docs/api/yii/base/baseobject/index.md#method-className) static | Returns the fully qualified name of this class. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-detach"></span>[`detach()`](/docs/api/yii/base/behavior/index.md#method-detach) | Detaches the behavior object from the component. | [`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md) |
| <span id="method-evaluateAttributes"></span>[`evaluateAttributes()`](/docs/api/yii/behaviors/attributebehavior/index.md#method-evaluateAttributes) | Evaluates the attribute value and assigns it to the current attributes. | [`AttributeBehavior`](/docs/api/yii/behaviors/attributebehavior/index.md) |
| <span id="method-events"></span>[`events()`](/docs/api/yii/behaviors/attributebehavior/index.md#method-events) | Declares event handlers for the [`$owner`](/docs/api/yii/base/behavior/index.md#property-owner)'s events. | [`AttributeBehavior`](/docs/api/yii/behaviors/attributebehavior/index.md) |
| <span id="method-hasMethod"></span>[`hasMethod()`](/docs/api/yii/base/baseobject/index.md#method-hasMethod) | Returns a value indicating whether a method is defined. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-hasProperty"></span>[`hasProperty()`](/docs/api/yii/base/baseobject/index.md#method-hasProperty) | Returns a value indicating whether a property is defined. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| [`init()`](#method-init) | Initializes the object. | `TimestampBehavior` |
| [`touch()`](#method-touch) | Updates a timestamp attribute to the current timestamp. | `TimestampBehavior` |
| [`getValue()`](#method-getValue) protected | Returns the value for the current attributes. | `TimestampBehavior` |

## Property details

### $updatedAtAttribute <span id="property-updatedAtAttribute"></span>

```php
public string|false $updatedAtAttribute = 'updated_at'
```

The attribute that will receive timestamp value.

Set this property to false if you do not want to record the update time.

### $value <span id="property-value"></span>

```php
public mixed $value = null
```

In case, when the value is `null`, the result of the PHP function [time()](https://www.php.net/manual/en/function.time.php)
will be used as value.

This can be an anonymous function,
callable in array format (e.g. `[$this, 'methodName']`), an [Expression](/docs/api/yii/db/expression/index.md) object representing a DB expression
(e.g. `new Expression('NOW()')`), scalar, string or an arbitrary value. If the former, the return value of the
function will be assigned to the attributes.
The signature of the function should be as follows,

```
function ($event)
{
    // return value will be assigned to the attribute
}
```

## Method details

### init() <span id="method-init"></span>

```php
public function init(): mixed
```

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the
given configuration.

**Returns**

`mixed`

### touch() <span id="method-touch"></span>

```php
public function touch(string $attribute): mixed
```

Updates a timestamp attribute to the current timestamp.

```
$model->touch('lastVisit');
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$attribute` | `string` | The name of the attribute to update. |

**Returns**

`mixed`

**Throws**

- [`yii\base\InvalidCallException`](/docs/api/yii/base/invalidcallexception/index.md): if owner is a new record (since version 2.0.6).

### getValue() <span id="method-getValue"></span>

```php
protected function getValue(mixed $event): mixed
```

Returns the value for the current attributes.

In case, when the [`$value`](/docs/api/yii/behaviors/timestampbehavior/index.md#property-value) is `null`, the result of the PHP function [time()](https://www.php.net/manual/en/function.time.php)
will be used as value.

This method is called by [`evaluateAttributes()`](/docs/api/yii/behaviors/attributebehavior/index.md#method-evaluateAttributes). Its return value will be assigned
to the attributes corresponding to the triggering event.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$event` | `mixed` | The event that triggers the current attribute updating. |

**Returns**

`mixed`: The attribute value