如何根据国家时区显示时间

时间:2012-03-31 16:57:22

标签: php time

当我访问我在美国托管的网站并且我正在从巴基斯坦查看时,它实际上向我展示了美国的时间和日期,

3 个答案:

答案 0 :(得分:2)

您可以使用date-default-timezone-set()功能设置您的时区。

答案 1 :(得分:1)

您可以为脚本创建函数DisplayDate($ datetoconvert),将时间转换为您的时间 - 并返回新的时间。

DisplayDate($xtime) //assuming its a unix timestamp..
{
$mydifferece = 6; // hours

$newtime = $xtime+($mydifference*3600); //
$newtime = date("d-m-Y H:i:s", $newtime);

return $newtime;

}

// HTML

撰写者:'。DisplayDate($ timewritten)。';

所有用户的功能时间..

  • “session”表现在应该有“timezone”列 - 供用户输入他们的时区,varchar(3)默认没有
  • 我们应该选择带时区的选项!

//让我们向用户显示实际时间..

//$xtime is database entry to be converted (if any)

//$usertimezone is a selected timezone by user, driven from session (guests) - or users table.. (ie +6, or -7, or +1 and so on..)


       DisplayDate($xtime="",$usertimezone="") 
        {
          if(!$xtime) //given time (to be converted) dont exists, okay - lets give some right now time..
          {
          $xtime = time(); //set time to "right now", unix timestamp
          }

         //now we have time, lets see if user selected his timezone..
         if($usertimezone != "") //someone selected his timezone, time to do the job..
         {  
//herein (additionally) we should add support for winter and summer time (daylight) - if that zone support that changes.. but im leaving that empty for now..

         $xtime = $xtime+($usertimezone*3600); //difference * seconds per hour
         }
         else
         {
         //usertimezone not set, user dont care about his time to be displayed correctly, or its just a bot or spider, so do nothing..
         }

         $xtime = date("j. m, Y. H:i:s", $xtime); //lets just do some cosmetics..

         return $xtime;
    }

// HTML

//来自数据库 - 即用于显示评论或文章datecreated times ..

echo DisplayDate($comment['commentdate'],$session['usertimezone']);

//显示时钟让我们说..

echo DisplayDate('',$session['usertimezone']);

答案 2 :(得分:0)

以UTC时区存储日期,将用户的时区偏好设置存储在其个人资料中,然后在首选时区显示该用户的日期。

<?php

// assume these preferences came from a database as-is
$userTimezonePreference = 'America/Denver';
$storedDateTimeAsUtc    = '2012-04-02 06:15:40';
$dateTime               = new DateTime($storedDateTimeAsUtc, new DateTimeZone('UTC'));

echo 'ORIG: ', $dateTime->format(DateTime::RFC2822), PHP_EOL;
$dateTime->setTimezone(new DateTimeZone($userTimezonePreference));
echo 'USER: ', $dateTime->format(DateTime::RFC2822), PHP_EOL;