Setting MySQL timezone for session - php

I know that using this query I can set time per session in mysql server
SET SESSION time_zone = '+04:00'
Question is how to detect this +04:00 (it can vary during year because of daylight saving time) part in PHP for my country?

Try using the timezone name (like America/Chicago) instead of +/- a set of hours. This should take into account daylight savings time.
You will need to load zoneinfo into your mysql database if you haven't already.

I will take a guess that perhaps you are in Azerbaijan? If so, you should use the IANA time zone id of Asia/Baku. This time zone alternates between a standard offset of +4:00 and a daylight offset of +5:00.
See "Time Zone != Offset" and "Time Zone Databases" in the timezone tag wiki.
If you need to do this in MySQL, you will need to load the IANA time zone database (aka "zoneinfo") into MySQL using mysql_tzinfo_to_sql. Thanks to datasage and kordirko for this tip.
But often the better approach is to only store UTC times in your database. You can do timezone translations directly in PHP using the DateTime and DateTimeZone classes. PHP also implements the same IANA time zone database, and you can find Asia/Baku on PHP's list of supported time zones.

Open your my.ini file. For windows it is in /mysql/bin/my.ini
Search for the section mysqld.
in this section enter -
default-time-zone = '+00:00'
+00:00 is the offset from GMT. Check out the time-zone-support page for better reference.

Related

Setting UTC as time zone in PHP and MySQL

I'm working on an application and I ran into a little problem...
How do I work with time zones and will there be conflicts between PHP and MySQL? What I was thinking of doing is setting the time zone to UTC in PHP like this date_default_timezone_set('UTC'); and storing it in MySQL using DATETIME.
Will MySQL change the time I provide via PHP to whatever time zone it has set or will it just store the value provided? If it will change it, how can I set the time zone in MySQL to UTC as well.
I would like to set the time zone to UTC so if I ever do need to worry about changing time for different time zones, I can just add/subtract whatever the offset is.
P.S. I'm new to web development.
Use below code to extract TimeZone Offset value. Then add it to your actual date time value. It will convert your Date Time value to UTC time.
set #TimeZoneOffSet := TIMEDIFF(NOW(),UTC_TIMESTAMP);
select ADDTIME(date_time_column,#TimeZoneOffSet) from table_name;;

Joomla timezone different from MySQL timezone

In Joomla I've correctly set my timezone to Eastern Time. I'm running my server locally with xampp. I can see that in my php.ini that my date.timezone is set to America/New_York, also Eastern Time. However, somehow, whenever anything is modified in Joomla, the time that appears in the database for modified is 5 hours ahead.
I don't know Joomla in depth, but this looks like it's by design:
Time Offset: Identifies the time zone in which the web site is to operate. The time offset is set in hours +/- between the web site location and UTC (Universal Time Coordinated - formerly referred to as GMT (Greenwich Mean Time)). Select the time zone from the drop down list.
Joomla seems to store UTC dates internally, and to calculate the difference when outputting data. So unless there are wrong dates visible in the front-end, I think this is fine.
Your MySQL timezone is probably off. Whenever your script calls MySQL date/time functions like NOW() it will use the MySQL time. You can see what the current timezones are set to by running this query SELECT ##global.time_zone, ##session.time_zone;.
Read more about it here

Store UTC date time in database

I will convert all date & time input by user (local time) to UTC and store it in database. When display back I will convert UTC time to their time zone which is set in their profile. Is it good?
I think it's good enough. Besides storing user timezone in profile, you can also let client (for example, javascript) convert UTC time according to user computer time zone.
As long as you can convert to/from any time zone from your stored DB records, that's all you need.
What you've described will work.
Note some MySQL documentation in regards to timezone & server/client workings:
Per-connection time zones.
Each client that connects has its own time zone setting, given by the session time_zone variable. Initially, the session variable takes its value from the global time_zone variable, but the client can change its own time zone with this statement:
mysql> SET time_zone = timezone;
So, normally, in your proposed solution, all is right, but don't let the actual server or client timezone changing catch you of guard.

What's the best way to manage dates across PHP, MySQL, etc?

My server is in Dallas. I'm in New York City.. and both PHP and MySQL have configuration variables for setting the timezone.
How do I get them all to work together? What dates should I store in MySQL? How do I get PHP to handle changing the date based on the user's preference?
Bear in mind: I don't think I'm ever having PHP explicitly set the date, it's always using "NOW()" in queries.. however I foresee the need to do this. How would this be done?
I'm hoping SO's experience can help me out here.
Use Unix Time everywhere. It's using UTC so it's the same for every timezone. Methods for dates usually convert to it and back from it using timezone information they have, so you would have yourself a correct time.
Alternatively you could use Unix Time only to transfer time from one computer to another (like from DB to your server running PHP, or to JavaScript client). There's functions to convert to it and from it in every language. For MySQL it is:
UNIX_TIMESTAMP(date)
FROM_UNIXTIME(unix_timestamp)
That way you could have your time properly formatted on the DB and in logs but still have correct local time everywhere.
I prefer using dates and times in the native form with respect to the environment, that is, Unix timestamps in PHP and DATE/TIME/DATETIME/TIMESTAMP fields in MySQL. I translate both values into another using FROM_UNIXTIME() and UNIX_TIMESTAMP(). I prefer this instead of Unix timestamps, because native dates/times are much easier to read.
Record your dates in GMT (zero offset) and then calculate the offset based on the local timezone (EST is +6, for example, so you'd add 6 hours to the GMT).
Check the Date docs for the date_default_timezone_set() function.
Just remember, when writing to the database, you'll have to change time zones, store the date, then change back. Likewise, when you're retrieving the date, don't forget to add the timezone offset.
The mysql-server stores dates in a timezone independent format (UTC).
But before it stores the date it will be converted using its timezone.
U can change the mysql timezone per connection *1:
mysql_query('SET time_zone = "'.$timezone.'"');
You can also change the timezone per script.
date_default_timezone_set($timezone);
If you set them to the same timezone "2009-01-10 13:30:00" will mean the same thing to both mysql and php.
But keep in mind that the 2 servers have different internal clock values, so if you want to generate timestamps based on current time. Do that in mysql OR php.
*1)
MySQL timezone support may require additional configuration. check the manual

Dealing with PHP server and MySQL server in different time zones

For those of us who use standard shared hosting packages, such as GoDaddy or Network Solutions, how do you handle datetime conversions when your hosting server (PHP) and MySQL server are in different time zones?
Also, does anybody have some best practice advice for determining what time zone a visitor to your site is in and manipulating a datetime variable appropriately?
As of PHP 5.1.0 you can use date_default_timezone_set() function to set the default timezone used by all date/time functions in a script.
For MySql (quoted from MySQL Server Time Zone Support page)
Before MySQL 4.1.3, the server operates only in the system time zone set at startup. Beginning with MySQL 4.1.3, the server maintains several time zone settings, some of which can be modified at runtime.
Of interest to you is per-connection setting of the time zones, which you would use at the beginning of your scripts
SET timezone = 'Europe/London';
As for detecting the client timezone setting, you could use a bit of JavaScript to get and save that information to a cookie, and use it on subsequent page reads, to calculate the proper timezone.
//Returns the offset (time difference) between Greenwich Mean Time (GMT)
//and local time of Date object, in minutes.
var offset = new Date().getTimezoneOffset();
document.cookie = 'timezoneOffset=' + escape(offset);
Or you could offer users the chioce to set their time zones themselves.
Store everything as UTC. You can do conversions at the client level, or on the server side using client settings.
php - date
mysql - utc-timestamp
RE the answer from Željko Živković, timezone descriptors like 'Europe/London' only work if the mySQL admin has added the timezone tables to the system, and keeps them updated.
Otherwise you are limited to numeric offsets like '-4:00'. Fortunately the php date('P') format provides it (as of 5.1.3)
So in say an app config file you might have
define('TZ', 'US/Pacific');
....
if (defined('TZ') && function_exists('date_default_timezone_set')) {
date_default_timezone_set(TZ);
$mdb2->exec("SET SESSION time_zone = " . $mdb2->quote(date('P')));
}
This means PHP and mySQL will agree on what timezone offset to use.
Always use TIMESTAMP for storing time values. The column is actually stored as UNIX_TIME (epoch) but implicitly converted from current time_zone offset when written, and back when read.
If you want to display times for users in other time zones, then instead of a global define(), set their given timezone in the above. TIMESTAMP values will be automatically converted by mySQL by the time your app sees the result set (which sometimes can be a problem, if you need to actually know the original timezone of the event too then it needs to be in another column)
and as far as, "why not just store all times as int's", that does lose you the ability to compare and validate dates, and means you always have to convert to date representation at the app level (and is hard on the eyes when you are looking at the data directly - quick, what happened at 1254369600?)
I save all my dates as a bigint due to having had issues with the dateTime type before. I save the result of the time() PHP function into it, now they count as being in the same timezone :)
In php set timezone by in the php.ini file:
ini_set("date.timezone", "America/Los_Angeles");
or in particular page you can do like:
date_default_timezone_set("America/Los_Angeles");
In mysql you can do like:
SET GLOBAL time_zone = 'America/Los_Angeles';

Categories