简体   繁体   中英

MySQL: CURDATE() with SET time_zone settings

I do set the time zone manually depending on user's settings with:

SET time_zone = "+02:00";

I want to get results where value is today from the +02:00 point of view.

WHERE time >= CURDATE()

But I am also gettings values from yesterday. The value in the table is for example:

2014-06-09 18:50:26

From 00:00 time zone (the time zone in which the value is stored in the database) the date above is today. But from the SET time_zone preference it is not. +02:00 would be:

2014-06-09 20:50:26

But still yesterday from users time zone.

So I don't want to get this result

SELECT time values from database works fine. They get converted to the -02:00 . But in the WHERE clause it somehow does not.

You can store all times in UTC and get it plus user timezone:

-- creating a test table
create table times(
    utc datetime
);

-- inserting some values 
insert into times 
     values (utc_timestamp()); -- must use utc_timestamp()

-- getting data converted for desired timezone
select utc, 
     date_add(utc,interval  '-5:00' hour_minute) as Lima,
     date_add(utc,interval  '1:00' hour_minute) as Madrid
from times;

+---------------------+---------------------+---------------------+
| utc                 | Lima                | Madrid              |
+---------------------+---------------------+---------------------+
| 2014-06-10 02:54:47 | 2014-06-09 21:54:47 | 2014-06-10 03:54:47 |
| 2014-06-10 02:55:46 | 2014-06-09 21:55:46 | 2014-06-10 03:55:46 |
| 2014-06-10 02:57:38 | 2014-06-09 21:57:38 | 2014-06-10 03:57:38 |
+---------------------+---------------------+---------------------+


-- You where clause would be and '-5:00' or '1:00' can be stored 
-- as session variable @user_timezone

where utc >= utc_timestamp()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM