2011-07-28 100 views
1

我有一些行的表並在他們那裏是是這樣一個定義:自定義時間更新

`metric_update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 

所以我真正想要做的是自動插入時的時間戳將數據插入到該表中。它確實如此。但我需要的是在該字段中寫入基於GMT的時間(當前服務器時間與GMT + 2類似)。

有沒有辦法對MYSQL說這樣的事情?

回答

0
INSERT INTO table_name(column1, metric_update_time) VALUES('dummy', CONVERT_TZ(CURRENT_TIMESTAMP,'+02:00','+03:00'); 

這將插入的時間戳轉換從GMT+2GMT+3

+0

好吧,我知道,但我可以把它定義喜歡: 'metric_update_time時間戳NOT NULL DEFAULT CONVERT_TZ(CURRENT_TIMESTAMP,' + 02:00' , '+ 03:00')」, –

+0

@Igor Hrcek:沒,你不能那樣做。 – Shef

2

如果您的服務器time and timezone settings配置正確,那麼內部all times stored in TIMESTAMP columns are converted to GMT(因爲這就是Unix timestamp mandates)。當您檢索這些數據時,它們會轉換回您的會話時區。如果您希望在GMT時區顯示,則需要在插入時不檢索數據時進行轉換。例如

請參閱下面的控制檯轉儲。你可以自己運行這些命令來檢查。

mysql> use test; 
Database changed 
mysql> -- let's create a table we'll be working with 
mysql> CREATE TABLE tsTable (
    -> ID INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
    -> ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP 
    ->); 
Query OK, 0 rows affected (0.08 sec) 

mysql> -- let's check current time as well as timezone settings 
mysql> SELECT CURTIME(),@@global.time_zone, @@session.time_zone; 
+-----------+--------------------+---------------------+ 
| CURTIME() | @@global.time_zone | @@session.time_zone | 
+-----------+--------------------+---------------------+ 
| 16:25:51 | SYSTEM    | +02:00    | 
+-----------+--------------------+---------------------+ 
1 row in set (0.05 sec) 

mysql> -- inserting empty row to table to trigger auto timestamp 
mysql> INSERT INTO tsTable VALUES (null,null); 
Query OK, 1 row affected (0.00 sec) 

mysql> -- looks like the time in my local timezone is stored in table 
mysql> SELECT * FROM tsTable; 
+----+---------------------+ 
| ID | ts     | 
+----+---------------------+ 
| 1 | 2011-07-28 16:26:25 | 
+----+---------------------+ 
1 row in set (0.00 sec) 

mysql> -- switching to GMT 
mysql> SET SESSION time_zone = '+0:00'; 
Query OK, 0 rows affected (0.00 sec) 

mysql> -- check current time and timezone settings again 
mysql> SELECT CURTIME(),@@global.time_zone, @@session.time_zone; 
+-----------+--------------------+---------------------+ 
| CURTIME() | @@global.time_zone | @@session.time_zone | 
+-----------+--------------------+---------------------+ 
| 14:27:53 | SYSTEM    | +00:00    | 
+-----------+--------------------+---------------------+ 
1 row in set (0.00 sec) 

mysql> -- note: CURTIME() returns time two hours 'earlier' than before 
mysql> -- let's see what's stored in the table again 
mysql> SELECT * FROM tsTable; 
+----+---------------------+ 
| ID | ts     | 
+----+---------------------+ 
| 1 | 2011-07-28 14:26:25 | 
+----+---------------------+ 
1 row in set (0.00 sec) 

mysql> -- TIMESTAMP is two hours 'earlier' than before too! Magick! 
+0

這只是很好的信息。我認爲Windows版本以不同的方式處理時區,不是嗎? –

+0

上面的代碼在Windows安裝上運行 – Mchl

+0

很棒的信息,謝謝! –