MySQL get the date n days ago as a timestamp

匿名 (未验证) 提交于 2019-12-03 00:46:02

问题:

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

Something like:

select now() - 30 

The result should return a timestamp.

回答1:

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 


回答2:

I think you are after DATE_SUB.



回答3:

You could use:

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

For unix timestamps or:

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

For the standard MySQL date format.



回答4:

If you need negative hours from timestamp

mysql>SELECT now( ) , FROM_UNIXTIME( 1364814799 ) , HOUR( TIMEDIFF( now( ) , FROM_UNIXTIME( 1364814799 ) ) ) , TIMESTAMPDIFF( HOUR , now( ) , FROM_UNIXTIME( 1364814799 ) )  2013-06-19 22:44:15     2013-04-01 14:13:19     1904    -1904 

this

TIMESTAMPDIFF( HOUR , now( ) , FROM_UNIXTIME( 1364814799 ) )  

will return negative and positive values, if you need to use x>this_timestamp

but this

HOUR( TIMEDIFF( now() , FROM_UNIXTIME( 1364814799 ) ) ) 

will return only positive, hours



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!