How to deal with PHP + MySQL timezones and MySQL GROUP BY [date] queries? -



How to deal with PHP + MySQL timezones and MySQL GROUP BY [date] queries? -

i'm working drupal 7, php, , mysql, , trying head around timezone issues when querying mysql database.

drupal handles dates pretty out of gate: dates stored utc timestamp int's in db, , timezone conversion happens on per-user basis via timezone setting in each user profile, using php 5's built-in timezone capabilities (so each time php script run script's timezone set current user's timezone).

so fine , dandy , painless long stick php.

things start tricky when bring in mysql, since there doesn't appear way synchronize current php script timezone given mysql query. seems best practice dictates handling timezone conversion in php: ever querying database raw timestamps, , converting in php necessary.

this seems reasonable in cases (even if bit slower @ times), but supposed mysql grouping [date] queries? instance, i'm building module handle analytics, , want things like:

group year(from_unixtime(u.created)), month(from_unixtime(u.created))

so run timezone issue...

possible solutions have come mind:

hard-code timezone: utilize date_default_timezone_set() within module insure php timezone set scheme timezone (so mysql timezone = php timezone). in other words, analytics timezone hard-coded, rather respecting timezone of user viewing analytics. isn't ideal, since want users in multiple timezones able access analytics using timezones. also, date_default_timezone_set() seems mess drupal up, sets timezone entire script, instead of within particular function...

forget using grouping in queries: fetch raw info db (be there tens or hundreds of thousands of rows), grouping results date in php using loops... solution seems more resource intensive, slower, , ridiculous.

so guess i'm asking is, have missed something? there best practice here i'm not aware of?

thanks ton help!

i consider approach such this

set time_zone = '+02:00';

http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html

and have

group from_unixtime(u.created, '%y-%m');

since from_unixtime bases it's time on time_zone, should give desired result.

to undo time_zone alter afterwards, consider saving select timediff(now(), convert_tz(now(), @@session.time_zone, '+00:00')); first , set saved value afterwards.

php mysql drupal datetime timezone

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -