IMB
IMB

Reputation: 15889

When converting dates to other timezone do you need to store the time?

When using PHP's DateTime to convert a stored date to a different timezone later, do you need to store the time information (e.g., 2012-12-31 00:00:00 instead of just 2012-12-31)? It appears that if I just store the date, the timezone conversion is inaccurate so I'm not sure if time information is really needed or I'm just missing something?

Upvotes: 0

Views: 72

Answers (2)

kmfk
kmfk

Reputation: 3951

Timezone conversions work by hour offsets - with out the time stored (atleast hours), you can't accurately calculate the difference.

An example to consider - say you want to group data by day, the dates are stored in UTC but your client is in PST.

A row was created on 2012-12-31 08:00:00 in UTC, but you stored 2012-12-31.

$date = new DateTime('2012-12-31', new DateTimeZone('UTC') );
echo $date->setTimezone( new DateTimeZone('America/Los_Angeles') )->format('Y-m-d');
//2012-12-30

$datetime = new DateTime('2012-12-31 08:00:00', new DateTimeZone('UTC') );
echo $datetime->setTimezone( new DateTimeZone('America/Los_Angeles') )->format('Y-m-d');
//2012-12-31

The date should reflect 2012-12-31 in PST, but with out the hour offset it would be converted incorrectly.

Also, as Samuel Cook answered, unless you explicitly store the datetime in your database under a single timezone, you should store the timezone as well, so you know what your converting from.

Upvotes: 1

Samuel Cook
Samuel Cook

Reputation: 16828

As well as saving the time you should also save the current timezone of that date that you are savings. This will effectively ensure that when you change to other timezones you know what to base the time off of.

Ex: 2012-11-21T15:52:01+0000

More information here

Upvotes: 1

Related Questions