Monday 12 November 2018

MySQL query for current GMT time

This sounds simple enough but I haven't been able to figure out how to use a
 simple SELECT statement to return the current time in GMT.
I have been trying to use CONVERT_TZ() to convert NOW() to GMT based on 
the server time zone and the GMT time zone but for some reason it returns 
NULL when I put in the text time zones. The only way I get a result is to actually 
put in the offsets which is getting way too complicated for what should be a 
really simple operation. Here is what I mean:
mysql> SELECT CONVERT_TZ(NOW(),@@global.system_time_zone,'GMT');
NULL

mysql> SELECT CONVERT_TZ(NOW(),'PST','GMT');
NULL

mysql> SELECT CONVERT_TZ(NOW(),'-08:00','+00:00');
2010-02-13 18:28:22
All I need is a simple query to return the current time in GMT. 

 Answers


Just use UTC (doesnt get affected with daylight savings time)
SELECT UTC_TIMESTAMP();

Old Content for reference:
this should work, but with
SELECT CONVERT_TZ(NOW(),'PST','GMT');
i got also NULL as result. funny enough the example in the mysql docu also returns null
SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');
you could try:
SET @OLD_TIME_ZONE=@@TIME_ZONE;
SET TIME_ZONE='+00:00';
SELECT NOW();
SET TIME_ZONE=@OLD_TIME_ZONE;
ok is not exactly what you wanted (its 4 queries, but only one select :-)






After seeing all the answers above and seeing it's unreliable to convert to PST, 
I just used this:
DATE_SUB(user_last_login, INTERVAL 7 hour)



When the source server timestamp is unknown but the requirement is for a 
specific tz do this:
select convert_tz(utc_timestamp(),'+05:00','+00:00')
This uses CST as an example. utc_timestamp will guarantee a '+00:00' result no 
matter where you query it. The '+05:00' is your desired offset. This works great when 
hitting multiple unknown servers and it assures you that you returning result will all be
 in a common tz result set.



This should work SELECT date_add(UTC_TIMESTAMP(), interval 330 minute);

0 comments:

Post a Comment