PHP timestamp date for custom timezone

I pull the raw generated mysql timestamp information from $ item_date from the database in php date format:

if (($timestamp = strtotime($item_date)) === false) { echo "The timestamp string is bogus"; } else { echo date('j MY h:i:sA', $timestamp); } 

Exit Server Zone (UTC):

12 Nov 2012 05:54:11 PM

but I want it to be converted according to the user's time zone

Example: let's say if the user time is November 13, 2012 07:00:00 (+0800 GMT) , and the server time is November 12, 2012 11:00:00 (UTC) and the timestamp is $ item_date November 12, 2012 10:30 : 00 (UTC) , therefore

A user with (UTC) will see $ item_date as:

November 12, 2012 10:30:00 PM

and user with (+0800 GMT) will see $ item_date as:

November 13, 2012 18:30:00

How can I do it? Thanks

+7
source share
1 answer

This post has been updated to include a complete example.

 <?php session_start(); if (isset($_POST['timezone'])) { $_SESSION['tz'] = $_POST['timezone']; exit; } if (isset($_SESSION['tz'])) { //at this point, you have the users timezone in your session $item_date = 1371278212; $dt = new DateTime(); $dt->setTimestamp($item_date); //just for the fun: what would it be in UTC? $dt->setTimezone(new DateTimeZone("UTC")); $would_be = $dt->format('Ymd H:i:sP'); $dt->setTimezone(new DateTimeZone($_SESSION['tz'])); $is = $dt->format('Ymd H:i:sP'); echo "Timestamp " . $item_date . " is date " . $is . " in users timezone " . $dt->getTimezone()->getName() . " and would be " . $would_be . " in UTC<br />"; } ?> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min.js"></script> <script language="javascript"> $(document).ready(function() { <?php if (!isset($_SESSION['tz'])) { ?> $.ajax({ type: "POST", url: "tz.php", data: 'timezone=' + jstz.determine().name(), success: function(data){ location.reload(); } }); <?php } ?> }); </script> 

Hopefully this is clear enough now;).

+20
source

All Articles