Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store UNIX timestamps with MySQL

Tags:

Some background:

My website depends heavily on coordinating users across all kinds of different time zones.

I am using Carbon to handle my time zone conversions and calculations on the server side and moment.js on the client.

As a result the design choice was made that all date times (e.g. the start time of an event) would be stored as unix timestamps.

Problem

I am a bit confused by the definition of a "timestamp". In PHPMyAdmin the timestamp is not a unix timestamp but rather a date format:

2016-10-06 20:50:46 

So if you want to have a default field of the current timestamp then you get the current date in GMT.

This makes things more complicated to convert back into a users timezone compared to a unix timestamp integer...

Question:

What field type should I store my unix timestamps as, currently I am using int(11) with a default of none. By extension... is there a way to store the current unix timestamp (e.g. 1475971200) by default in MySQL?

like image 658
Jethro Hazelhurst Avatar asked Oct 06 '16 19:10

Jethro Hazelhurst


People also ask

How are timestamps stored in MySQL?

MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME .) By default, the current time zone for each connection is the server's time.

What is Unix timestamp MySQL?

UNIX_TIMESTAMP() function in MySQL We can define a Unix timestamp as the number of seconds that have passed since '1970-01-01 00:00:00'UTC. Even if you pass the current date/time or another specified date/time, the function will return a Unix timestamp based on that. Syntax : UNIX_TIMESTAMP() UNIX_TIMESTAMP(date)

What datatype is used to store Unix timestamps?

A Unix timestamp is a large integer (the number of seconds since 1970-01-01 00:00:00 UTC), so INT(11) is the correct datatype.

What is the difference between Unix timestamps and MySQL timestamps?

In MySQL, UNIX TIMESTAMPS are stored as 32-bit integers. On the other hand MySQL TIMESTAMPS are also stored in similar manner but represented in readable YYYY-MM-DD HH:MM:SS format.


1 Answers

A Unix timestamp is a large integer (the number of seconds since 1970-01-01 00:00:00 UTC), so INT(11) is the correct datatype.

Unfortunately, I don't think there's any way to specify a default that will insert the current timestamp. You'll need to call UNIX_TIMESTAMP() explicitly when inserting, and use that. Function calls aren't allowed in DEFAULT specifications.

like image 63
Barmar Avatar answered Sep 30 '22 15:09

Barmar