MySQL ottiene la data n giorni fa come timestamp


99

In MySQL, come potrei ottenere un timestamp, diciamo 30 giorni fa?

Qualcosa di simile a:

select now() - 30

Il risultato dovrebbe restituire un timestamp.


Penso che tu stia cercando DATE_SUB .
joeslice

1
Quale formato di timestamp? C'è il formato con cui le persone che lavorano con le funzioni MySQL DATE hanno familiarità e c'è un timestamp in stile UNIX.
joebert

Sto cercando il Timestamp di MySQL.
Ben Noland,

Risposte:


181

DATE_SUB ne farà parte a seconda di ciò che desideri

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

11
Qual è la differenza con la prima e la seconda query?
Codler

5
sembra che (v1) DATE_SUB restituirà DATETIME o STRING a seconda degli input. TIMESTAMP (v2) lo impone a un tipo TIMESTAMP. dev.mysql.com/doc/refman/5.1/en/…
jsh

3

Potresti usare:

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

Per timestamp unix o:

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

Per il formato di data MySQL standard.


0

Se hai bisogno di ore negative dal 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

Questo

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

restituirà valori negativi e positivi, se è necessario utilizzare x> this_timestamp

ma questo

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

tornerà solo positivo, ore

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.