Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create field with default as epoch time

Tags:

sql

mysql

I need to create a timestamp field for a table who's rows need to expire after a certain amount of time. If I use the following:

`timestamp` TIMESTAMP DEFAULT NOW(),

It shows the time in a human readable format, it would be a lot easier if I could have it in epoch time so I can calculate with seconds. Is there a way I can create a field that will display the current time when a row is created in epoch time by default? Thanks!

like image 904
Ben Kulbertis Avatar asked Aug 15 '10 01:08

Ben Kulbertis


1 Answers

You may want to use the UNIX_TIMESTAMP() function in your SELECT statements, as in the following example:

CREATE TABLE test_tb (`timestamp` TIMESTAMP DEFAULT NOW());
INSERT INTO test_tb VALUES (DEFAULT);

SELECT UNIX_TIMESTAMP(`timestamp`) epoch, `timestamp` FROM test_tb;
+------------+---------------------+
| epoch      | timestamp           |
+------------+---------------------+
| 1281834891 | 2010-08-15 03:14:51 |
+------------+---------------------+
1 row in set (0.00 sec)
like image 76
Daniel Vassallo Avatar answered Sep 18 '22 15:09

Daniel Vassallo