Saturday, February 5, 2011

MySQL get the date n days ago as a timestamp

In MySQL, how would I get a timestamp from, say 30 days ago?

Something like:

select now() - 30

The result should return a timestamp.

  • I think you are after DATE_SUB.

    From joeslice
  • You could use:

    SELECT unix_timestamp(now()) - unix_timestamp(maketime(_,_,_));
    

    For unix timestamps or:

    SELECT addtime(now(),maketime(_,_,_));
    

    For the standard MySQL date format.

  • DATE_SUB will do part of it depending on what you want

    mysql> SELECT DATE_SUB(NOW(), INTERVAL 30 day);
    2009-06-07 21:55:09
    
    mysql> SELECT TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 day));
    2009-06-07 21:55:09
    
    mysql> SELECT UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 day));
    1244433347
    

0 comments:

Post a Comment