3

I have a dropdown box on a webpage that takes a timezone identifier as the value (however I can change it to save the GMT offset if that is a better choice). Currently a user would be saving something like "America/Denver" as his / her time zone.

I need to convert a unix timestamp into the user's local time for display in another portion of the page. What is the best way to accomplish this?

Would it be better to store the GMT offset in the database and use that for a time calculation? Can someone please point me in the right direction here?

Thanks!

1 Answer 1

5

The easiest approach would be to use DateTime with:

$t = new DateTime();
$t->setTimestamp( $time=time() );
$t->setTimeZone(new DateTimeZone("America/Denver"));
print $t->format(DateTime::RFC850);

The timezone can be changed at will to cause the format function to recalculate the local time.

Sign up to request clarification or add additional context in comments.

10 Comments

That's just a format string, like in date(). You can use any of those predefined in de.php.net/manual/en/class.datetime.php or supply your own ->format("d.M.y H:i:s");
So I tried to set up the way you outlined above and I got this error message "Uncaught exception 'Exception' with message 'DateTime::__construct() [<a href='datetime.--construct'>datetime.--construct</a>]: It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for 'EDT/-4.0/DST'"
Interesting. Then construct it like new DateTime("now", new DateTimeZone("America/New_York")); - It should be possible to override this later, and changing the timestamp alike. Or really try the procedural version and preface everything with date_default_timezone_set("America/New_York");
would I be able to feed in a unix timestamp in place of "now" ?
No, only as second step. The init parameter must be a formatted time string.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.