会话变量不能实时工作

I have a user comment system in which time of comment is displayed using UTC timestamp stored in database along with comments.

The time offset is used to set session timeoffset variable using javascript post request to get user local time.

I have done like this because user are from diffrent timezone and I cannot store time In one time zone alone so I have stored it in UTC and then displayed using timeoffset of timezone.

This system is not working in real time but working after refresh.

comments.php

<?php 
session_save_path('session/store');
session_start();
?>

<script type="text/javascript" src="jquery/jquery.js"></script>
<script type="text/javascript">
var timeoffset = new Date().getTimezoneOffset();

$.post('timeoffset.php', {timeoffset:timeoffset}, function(data){
    //alert(data);
});
</script>

<?php
if(isset($_SESSION['timeoffset'])&&!empty($_SESSION['timeoffset'])){
    date_default_timezone_set('UTC');
    $timeoffset = (int)$_SESSION['timeoffset'];
}
else{
    echo 'timeoffset not set';
    exit;
}

 // here are comments displayed using while loop
 // time of comments is displayed like this
 echo gmdate("F j, Y, h:i:s a", $row['timestamp']-($timeoffset*60)); //$row['timestamp'] = UTC time stamp stored in database. e.g: 1377509788
?>

timeoffset.php

<?php session_save_path('session/store');
session_start();

if(isset($_POST['timeoffset'])){
    $_SESSION['timeoffset'] = (int)$_POST['timeoffset'];
    echo $_SESSION['timeoffset'];
}
?>

It shows timeoffset not set first and then after refresh it shows comments and time.

Please see and suggest any possible way to do this.

Thanks.

The PHP code is executed before the user gets the page displayed. Because of that, it doesn't matter if the code is in the document before or after the javascript code which is executed in the client's browser. So you have to add the time via javascript and ajax, too. The alet in your post request should give you the right result.