Xeoncross
Xeoncross

Reputation: 57234

PHP + MySQL Building server timezone agnostic scripts?

When building PHP applications I always end up having trouble trying to get everything to play right with server times and timezones.

I generally have a simple timestamp-like field on most of my records that isn't updated - just static for reference purposes. I use it to track when events happened, when users registered, when comments were created etc.

I have been trying to follow the best practices of using a Datetime field to store this value. The problem is that when using different servers they often have different timezones so the datetime's don't match up even close unless I add more code to offset the differences. This can also be a problem when using MySQL replication and NOW() queries since their is often a lag.

I'm wondering if I should go back to using ints since they don't seem to care anything about timezones and only require the server clock is set. The downfall is that all those MySQL date/time functions (I never use) can't be used which might be a problem in the future. The upside is that I can cut the storage space in half by moving back to 4byte ints instead of datetimes.

People also mention that ints will only work until 2037 - why is that a problem? Who expects to be using PHP + MySQL in 2037?

Is there anything I am missing? Is it better to store reference times in an agnostic way like Unix timestamps?

Upvotes: 1

Views: 196

Answers (1)

phemmer
phemmer

Reputation: 8807

I use date/time fields in all my database work but store everything in GMT. Pretty much the first opportunity my code gets it converts something into GMT, and does all its internal math in gmt, etc. The only time I convert it back out of GMT into local time is when displaying to the user. PHP has unixtime() which is GMT, plus gmstrftime and gmdate, pretty much anything you'll ever need.

Upvotes: 2

Related Questions