I work on an existing project that stores dates to a MySQL DB. The dates are stored as UTC since all users so far were in GTM+0 and no conversion was needed.
I now need to modify the code so that users from other time zones can use the system. The users choose their timezone when they register to the system, so I have a table holding the timezone for each user.
I know I can use CONVERT_TZ() when I extract and store the dates, but to do so means to go through all the queries and add this function.
When I do:
SET ##session.time_zone:='+7:00';
select now();
The result changes with the timezone variable.
When I do:
SET ##session.time_zone:='+7:00';
select myDate from myTable;
The result stays the same, returning what is stored in the DB.
Is there any way I can change the connection string or is there a session variable I can use that will affect the queries without having to add CONVERT_TZ to every single query?
Edit: this is not a duplicate of Should I use field 'datetime' or 'timestamp'? since using timestamp means I need to change all the date field in the DB, while I try to change something more global so I will not have to do massive changes the Db fields or the code.
Related
I have a table named "students" where student information are stored. Last week, I added a column (type-datetime) to keep track students last login time.
It was working well when testing with localhost. So, I uploaded to hosting and after a few days, I noticed datetime are different with my local times. I called now() function in my code and it is inserting with server time (Seattle,USA Time). I tried to set it with my timezone.
SELECT ##session.time_zone;
SET time_zone = 'Asia/Rangoon';
SET time_zone = "+06:30";
SET ##session.time_zone = "+06:30";
although it is executed, it don't affect and inserting with server time like before.
My Question is how should I update my existing datetime value column to my respective timezone. Thanks and appreciating.
The best approach imho is to save all dates in UTC. Only at presentation time these times should be converted to the time and zone for the user.
Because you are using PHP, you can convert input into UTC and convert output to the desired timezone for presentation.
This makes it also easy and possible to show foreign visitors their own time on your website.
How to change the display of dates in MySQL Workbench
Recorded as 16-01-2014 now
But is necessary to do so: 16-01-2014
You'll need to change your SELECT statements to get your dates rendered differently.
Change
SELECT datestamp
to
SELECT DATE_FORMAT(datestamp,'%d-%m-%Y')
MySQL Workbench is a client program that accesses MySQL database servers. You use the workbench to write queries to send to a MySQL server to get back data.
If you want your dates presented in a particular way, that's part of the queries you write. If you use the queries built in to the workbench, you can't change the date format it displays.
Don't give in to the temptation to change the data type of your date and time columns in your table to VARCHAR(), and then fill them with values in the format you prefer. If you do that, you'll lose the ability to search your table on date ranges.
I have a Django API application running on postgres with TIME_ZONE='America/New_York' and USE_TZ = True.
For a daily report, I need to query another database, MySQL, and compare records from the postgres DB to check for some updates. They should contain the same number of results. The MySQL DB's timezone is UTC however. How can I perform SELECT queries against the MySQL DB to have it match the same date range on my postgres DB?
Example:
These two queries should return the same number of results
# Django/Postgres with TIME_ZONE='America/New_York'`
MyObject.objects.filter(created_on__date=date(2016, 9, 17))
# External MySQL Databse in UTC
sql.execute('SELECT * from MY_TABLE where created_on BETWEEN "2016-09-17" AND "2016-09-18"')
What you need is to convert the date in MySQL to match America/New_York time zone.
The function to achieve that would be CONVERT_TZ() and since you need named time zone first you need to set up time zone tables.
If you are uncertain whether named time zones are available issue below query - if it returns zero the table is empty so using named time zones is unavailable and you need to populate them (I've mentioned a link to documentation above).
SELECT COUNT(*) FROM mysql.time_zone_name;
mysql_tzinfo_to_sql is used to populate time zones tables.
If your time zone is not a moving one then you can go with less safe, hardcored approach (not recommended) by explicitly typing the time difference like so:
mysql> SELECT CONVERT_TZ('2016-09-17 10:00:00','+00:00','+06:00');
-> '2016-09-17 16:00:00' -- Result
I'm working on a shared hosting so I don't have access to mysql configuration files.
The default timezone on that system is 'America/New_York' but I need to use UTC -5:00 for my databases.
Everytime I perform a query the timezone is set to UTC -5:00 like this:
SET time_zone='-5:00';
If I want the current time, SELECT NOW() returns the correct time and date, but when updating a table mysql uses the SYSTEM time and not the set timezone
UPDATE administradores SET ultimo_acceso=NOW() WHERE id=1
Why does those values are different? Shouldn't be the same time in both queries since I'm overriding the timezone?
I also tried with INSERT statement and that works fine.
If the ultimo_acceso field is of type TIMESTAMP, then the value is actually being stored as UTC and then converted back to the current time zone when you select the value back out. So you need to set the time zone again in the select statement.
If you are using a DATETIME data type, then the value you set should be persisted without conversion and you will get back exactly what you store - regardless of the timezone setting at time of select.
See the MySQL docs on this subject.
Note that DATETIME, DATE, and TIME fields will always return the exact time you placed into them, regardless of the value of the time_zone variable.
TIMESTAMP fields will automatically convert their values to the timezone specified by the time_zone variable.
I have the offset in seconds to UTC, all timestamps stored on the database are in UTC, how to apply the offset during selection queries,
mysql_query("SELECT * FROM table WHERE unix_timestamp=unix_timestamp with offset applied");
mysql_query("INSERT INTO table (unix_timestamp) VALUES(UNIX_TIMESTAMP())");
I'd want to insert in UTC time to the database and retrieve in local time.
On PHP:
date_default_timezone_set('UTC');
$user_timezone_offset=-7200; // -2
Could I substract on select's runtime of mysql to the unix_timestamp field $user_timezone_offset and that would be it?
I am inserting in UTC which is what I need apparently, but for selection in user's local time I'd need to apply the offset to the timestamp stored in the database somehow.
Edit: I just came across this:
$user_timezone_offset="-2:00";
FROM_UNIXTIME(CONVERT_TZ(unix_timestamp,'+00:00','$user_timezone_offset'))
Would need to know how to apply it to a select query making the selection of unix_timestamp converted for comparison inside the select and the result also becoming modified for php's fetch_array
This seems to be the solution:
SELECT *, Unix_Timestamp(CONVERT_TZ(FROM_UNIXTIME(unix_timestamp), '+00:00', '$user_timezone_offset')) as unix_timestamp
Actually this has a problem - although on
mysql_fetch_array($result){ $row['unix_timestamp']; }
comes converted while checking on
WHERE unix_timestamp=value //assuming unix_timestamp
to be converted on the select - in there it is not converted and another
Unix_Timestamp(CONVERT_TZ(FROM_UNIXTIME(unix_timestamp), '+00:00', '$user_timezone_offset'))
has to be called for unix_timestamp to be "converted" each time a check is to be made against the converted value.
I think you may be overcomplicating the issue.
Timestamps are always UTC. When you retrieve a timestamp in PHP, it is in UTC.
When you convert a timezone using the date() function for example, it displays in whatever timezone the php.ini setting date.timezone is set to.
Therefore, if you have users with specific timezones, just call date_default_timezone_set() with the appropriate timezone prior to displaying dates in local time.
If you use the DateTime class, then you can specify the desired timezone when you construct the object.
Unless you have a very specific reason, there should be no need to perform timezone conversions when you fetch timestamps from the database. PHP handles this all for you.