2011-07-28 68 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

很棒的信息,谢谢! –