Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL compare unix timestamps

Tags:

date

mysql

I'm trying to get all records which have a date_created within 2 hours ago. It's a unix timestamp which is created from the php function time(). Here is my current query:

SELECT id from gsapi_synsets where name = "Beyonce" and date_created BETWEEN  UNIX_TIMESTAMP(date_created) and UNIX_TIMESTAMP(DATE_ADD(CURDATE(),INTERVAL 2 hour))    

Doesn't seem to be working though.

like image 985
somejkuser Avatar asked Aug 09 '13 18:08

somejkuser


People also ask

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.

Can you compare timestamps in SQL?

A date, time, or timestamp value can be compared with another value of the same data type, a datetime constant of the same data type, or with a string representation of a value of that data type.

What is Unix timestamp in 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. Parameters : It will accept only one argument.

How do I get epoch in MySQL?

MySQL - UNIX_TIMESTAMP() Function Where a time stamp is a numerical value representing the number of milliseconds from '1970-01-01 00:00:01' UTC (epoch) to the specified time.


2 Answers

If none of the date_created values will be in the future, you can use this:

SELECT id
FROM gsapi_synsets
WHERE name = 'Beyonce'
  AND date_created > UNIX_TIMESTAMP(NOW() - INTERVAL 2 HOUR);

If date_created values can be in the future, use this, which cuts off at the current

SELECT id
FROM gsapi_synsets
WHERE name = 'Beyonce'
  AND date_created BETWEEN UNIX_TIMESTAMP(NOW() - INTERVAL 2 HOUR) AND UNIX_TIMESTAMP()

Note that calling UNIX_TIMESTAMP without an argument returns the timestamp for "right now".

like image 154
Ed Gibbs Avatar answered Sep 28 '22 08:09

Ed Gibbs


You're trying to get all row's between that row's datestamp and 2 hours from now, which won't work. Use this instead:

SELECT id from gsapi_synsets where name = "Beyonce" and date_created BETWEEN  UNIX_TIMESTAMP(DATE_ADD(NOW(),INTERVAL -2 hour)) and  UNIX_TIMESTAMP(NOW())     
like image 25
aynber Avatar answered Sep 28 '22 08:09

aynber