How to set current time for timestamp and datetime type in magento object save repository?

Timestamp and DateTime type of MySQL is used to set date and date/time value to the database table.

Both types contain the default attribute called default=”CURRENT_TIMESTAMP” to use the set current time in the table.

While you are working with the db_schema.xml file and need to add/update the current time in the table for any specific object save repository, you can set the default attribute with the value CURRENT_TIMESTAMP to save current time while placing an entry in the database table.


For the timestamp type field,

<table name="my_table_name" resource="default" engine="innodb" comment="My table name">
    <column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" comment="Created At"/>
</table>

For DateTime type field,

<table name="my_table_name" resource="default" engine="innodb" comment="My table name">
    <column xsi:type="datetime" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" comment="Created At"/>
</table>

Here in the column created_at, We need to set default=”CURRENT_TIMESTAMP”  to save the current time in the table.

This will be helpful when you want to track the time when any entry is added to the tables. This will be automatically set the current time in the table column.