8

$item_date の未加工の生成された mysql タイムスタンプ情報をデータベースから php 日付形式として取得しています。

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

サーバー ゾーン (UTC) に続く出力:

2012 年 11 月 12 日 05:54:11PM

しかし、ユーザーのタイムゾーンに従って変換したい

例: ユーザーの時刻が2012 年 11 月 13 日 07:00:00 AM (+0800 GMT)で、サーバー時刻が2012 年 11 月 12 日 11:00:00 PM (UTC)で、$item_date のタイムスタンプが2012 年 11 月 12 日であるとします。 22:30:00 (UTC)なので

(UTC)のユーザーには、 $item_date が次のように表示されます。

2012 年 11 月 12 日 午後 10 時 30 分

(+0800 GMT) のユーザーには、$item_date が次のように表示されます。

2012 年 11 月 13 日 06:30:00 午後

どうすればそれを成し遂げることができますか? ありがとう

4

1 に答える 1

25

この投稿は、本格的な例を含むように更新されました

<?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('Y-m-d H:i:sP');

        $dt->setTimezone(new DateTimeZone($_SESSION['tz']));
        $is = $dt->format('Y-m-d 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>

これで十分に明確になったことを願っています;)。

于 2012-11-12T07:06:57.813 に答える