Convert value set with ON UPDATE CURRENT_TIMESTAMP to UTC - mysql

In MySQL a field was created with ON UPDATE CURRENT_TIMESTAMP designation. This saves the record update date in the server's timezone. I want to convert this time to UTC time.
The server is hosted in an account that doesn't have access to the server administration or the MySQL administration so I can't set the timezone on the server or MySQL directly through command line interfaces or startup files or any other way. This includes the SET time_zone command or the my.cnf file.
I also found a suggestion to use ON UPDATE UTC_TIMESTAMP but found this gives a syntax error and is not supported in the documentation.
So what I am trying to do now is to find a select clause that converts the value saved by ON UPDATE CURRENT_TIMESTAMP, which is saved in the server's current timezone, and convert it to UTC time.
Ideally this clause would detect the server's timezone so the value is not hardcoded and works with whatever timezone the server is set to.

Since nobody answered this question here is the workaround I ended up using:
Since I access mySQl from php I used php to solve the problem by calculating the difference in seconds from server time to UTC then subtracting that amount in the SQL statement.
Here is the PHP function to calculate the difference in seconds from server time to utc:
function utcOffset() {
$serverTime = new DateTime('NOW');
return $serverTime->getOffset();
}
Here is how I built the SQL statement in PHP to select time in utc in seconds since 1-1-1970:
$sql .= "SELECT TIMESTAMPDIFF(SECOND, '1970-01-01', myServerTimeStampField)-".utcOffset()." AS timeInUTCSeconds FROM myTable";

Related

Exporting with phpMyAdmin changes timestamps

When exporting a file through phpMyAdmin some timestamps are put back an hour. How may I prevent this? I do not want timestamps tampered with. Here's a screenshot for the curious (see the dates.)
I believe the cause may be the SET time_zone = "+00:00"; that is added to every export file.
Is this suppose to happen? Is it a known bug?
I'm running:
-- Server version: 5.5.37-0ubuntu0.14.04.1
-- PHP Version: 5.5.9-1ubuntu4
The times are not actually being 'tampered with'.
MySQL interally stores TIMESTAMP columns converted to UTC time, then uses a mixture of system and session (client session) values to determine what to display to the user.
You can check both of these values running the following query yourself.
SELECT ##global.time_zone, ##session.time_zone;
So when your PHPMA script generates its dump, its specifying a session time_zone variable so when you run it MySQL will convert them all from that timezone back to UTC. When you then go to import that to another database, it will still convert them back to the UTC values you're expecting.
So to summarise if the values in the dump with SET time_zone = "+00:00"; are all "1 hour behind" the values you see when querying via PHPMyAdmin, this only appears this way because the connection via PHPMyAdmin will have it's timezone one hour ahead of UTC.

Mysql: Set time_zone for select queries, UTC for everything else

Is it possible to configure MySQL (at runtime) to use UTC for all write queries, but another timezone for all SELECT queries?
I'm storing all dates in UTC (additionally, the app will always pass UTC datetimes to MySQL) and have MySQL configured to be running in UTC (using SET time_zone = '+0:00'); but is there a way for it to automatically translate all SELECT into another timezone?
I realise I can do this in code, but if I can make MySQL do the job for me that'd be much easier.
To be clear: I'd also like to just run a command once, not use any of the date/time formatting functions for each query.
User CONVERT_TZ() in mysql function
SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');
Ref : http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_convert-tz

Changing CURRENT_TIMESTAMP value based on timezone in MySQL

I want to migrate our mysql server from shared hosting to local server.
Current server is in MST time zone and the values for the CURRENT_TIMESTAMP in databsse is stored as -7:00 GMT.
Now I want to move complete application on dedicated server in India. Also want to convert the date values stored in -7:00 GMT to +5:30 GMT.
I can accomplish this task of updating the dates by writing script to update the time, however I would like to know if is there any way I can do this from database itself (at time of import or while exporting itself)
mysql version 5.0.96-log. I am not getting option export timestamp in UTC.
When using mysqldump, set the flag: --tz-utc to force all timestamps to be exported as UTC. ( http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_tz-utc ). Note here --tz-utc is enabled by default. So you should have to do nothing: but test first :)
If just working with timestamps on the server you don't have to do anything to convert them, from the documentation on TIMESTAMP post MySQL 4.1 ( http://dev.mysql.com/doc/refman/4.1/en/timestamp.html ):
"values still are stored in UTC, but are converted from the current
time zone for storage, and converted back to the current time zone for
retrieval. As long as the time zone setting remains constant, you
get back the same value you store. If you store a TIMESTAMP value, and
then change the time zone and retrieve the value, the retrieved value
is different from the value you stored."
This is easy to test:
Save a timestamp to your table
Change the server's timezone
Retrieve it: the return value should reflect the new timezone.
So another option is you could just have both the servers set to the same timezone while doing the export / import, than set them back to the correct timezone(s) after it is complete, but note with MySQLDump this should not be necessary.
General syntax
SELECT DATE_ADD(<column_name>, INTERVAL HOUR);
for changing to UTC to MST
SELECT DATE_ADD(NOW(), INTERVAL 7 HOUR);

Set MySQL database timezone to GMT

I need to change the timezone of a single database is this possible?
I know we can change the timezone within our WHM (we are using a dedicated server from hostgator), however a large number of legacy software running on the server has a lot of +6 hours coding in it (i.e. server timezone is CST, we wanted the time in GMT so previous developers altered date/times manually within the code - bad!).
I am now working on a new software and would like to have it all in GMT, I know I can use date_default_timezone_set('GMT') however that will not solve MySQL inserts where the datetime column is set to CURRENT_TIMESTAMP as it will insert # CST timezone.
No, it's not possible to change the timezone for a single database within a MySQL instance.
We can retrieve the server and client time_zone settings with a query, like this:
SELECT ##global.time_zone, ##session.time_zone;
We can also change the client timezone for a session, or change the timezone for the entire MySQL instance.
But we need to be keenly aware of the implication that this change will have on existing client connections, and the how DATETIME and TIMESTAMP values already stored in the instance will be interpreted.
To have the server time_zone set at MySQL instance startup, we can modify the /etc/my.cnf file (or wherever the mysql instance initialization parameters are read from), under the [mysqld] section:
[mysqld]
default-time-zone='+00:00'
-- or --
It is also possible (less desirable) to add the --default_time_zone='+00:00' option to mysqld_safe
NOTE: Changing the timezone setting on the MySQL server does NOT change the values stored in existing DATETIME or TIMESTAMP columns, BUT since it does effectively change the context in which those stored values are interpreted, it will look like all of the values ARE shifted. (Where 08:00 was taken to mean 8AM CST, with the time_zone of the server changed from CST to GMT, that same '08:00' will now be taken to be 8AM GMT, which would effectively be 2AM CST.
Also keep in mind that TIMESTAMP columns are always stored in UTC, while DATETIME columns do not have a timezone.
http://dev.mysql.com/doc/refman/5.5/en/datetime.html
Each client session can change the timezone setting for their own session:
SET time_zone='-06:00';
But none of this really "solves" the timezone conversion problem, it just moves the conversion problem around.
There's nothing inherently "bad" with the application layer handling timezone conversions; sometimes, that's the best place to handle. It just has to be done correctly and consistently.
(What's odd about the setup you describe is that the app is storing DATETIME values as if the MySQL server time_zone is set to GMT, but the MySQL server time_zone is set to something else.)
If you can't change your current time zone you can change the result.
date 2015-01-05 12:06:16
Select date + Interval 2 Hour 'date' From ExampleTable
date 2015-01-05 14:06:16
You can modify the the default value instead of entering current_timestamp make it insert current_timestamp added to hours offset of your timezone. I just did it this way when didn't found any solution, had to invent my own.

JDBC give MySQL datetime in UTC

My Java:
Date parsedDate = dateFormat.parse(timestamp);
Timestamp dbTimestamp = new Timestamp(parsedDate.getTime());
insertTimestampPreparedStatement.setTimestamp(3, dbTimestamp);
PhpMyAdmin/MySQL always displays this in my local time, even when I do
insertTimestampPreparedStatement.setTimestamp(3, dbTimestamp, Calendar.instance(TimeZone.getTimeZone("UTC"));
I'm not sure if MySQL stores them aware of timezone, and the only way I checked this was updating a timezone row to NOW() directly in phpmyadmin, and it then showed me a time in GMT. So either there is a bug in phpmyadmin/mysql or my code is not sending over timestamps in the correct timezone.
How do I get this to work in UTC?
A JDBC driver must use the local timezone when retrieving or storing timestamps, unless a Calendar with the specific timezone is provided.
Unfortunately, the JDBC spec isn't always clear on how drivers should behave, and it looks like MySQL does it wrong. For MySQL you can force the timezone it uses by specifying one or more options in the connection string serverTimeZone and related properties. See http://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html for a full list.