ygoe ygoe - 4 months ago 11x
PHP Question

Convert a UNIX timestamp into local time (as integer)

For a simple PHP graphing script, I need to align time values at local time days. When I do something like

$timestamp % 86400 == 0
I get a break at 2 am every day because I'm in UTC +2 here. Also all my grid lines are at 2am, 5am, 8am etc. instead of 0am, 3am, 6am etc.

I understand that UNIX timestamp integer values are always in UTC and that there's
and such, but I need an integer in local time to do arithmetics on it. How would I do that in PHP? Is there a function such as
like in .NET?

To clarify the question, I have nothing to do with readable formatting of the time. No YYYY-MM-DD HH:MM:SS or the like, I just deal with numbers. The input is a number of seconds since epoch in UTC, aka the UNIX timestamp. What I need is a number of the same kind but not in UTC but local time. So I need to convert a UNIX timestamp integer into a local timestamp integer. Hope this is understandable and anybody can imagine what this could be used for (aligning grid lines in a time-axis graph at local time).


I ended up using this to determine the local time UTC offset:

$tzoffset = date('Z');

Then I just add or subtract that value to timestamps and treat them like UTC times but they are really local times. Technically they are always "off" the real time I intend to work with, but that shift corrects the difference between UTC and local time and lets me do the maths on local times in the "UTC space". When I'm done, I can transform the time back into "local space" for displaying. I could also use the gmdate function and get local time format.

$now = time() + $tzoffset;
echo gmdate('...', $now);   // Prints local time
if ($now % 86400 == 0 && gmdate('w', $now) == 1)
    echo 'Monday midnight local time';