首页 > 解决方案 > 时间戳或根据时区更改时间

问题描述

我是这个论坛的新手,正在学习编码。

我想问一下如何将时间戳更改为当前时区,或者有什么方法可以将时间戳日期/时间转换为我当前的时区美国/多伦多或 -4:00

我尝试了所有可用于 MySQL 和 Cpanel 的选项。(htacces, phpini, mysql 中的 settimezone)

现在我打算用 PHP 做,因为它会更好。

这是从表中获取时间戳的代码

<?php echo htmlentities($result->PostingDate);?>

请告诉我将时间转换为当前时区的合适方法

标签: phpmysql

解决方案


如果您知道您的 PostingDate 设置的当前时区,并且您想使用 PHP 代码执行此操作,您可以尝试以下操作:

// Current timezone used by server, database
$current_timezone = new DateTimeZone('UTC'); 
// Your timezone that YOU want to use
$local_timezone = new DateTimeZone('America/Toronto');

$datetime = new DateTime($result->PostingDate, $current_timezone);
$datetime->setTimezone($local_timezone);

// $datetime should be set to America/Toronto now.

支持的时区列表:https ://www.php.net/manual/en/timezones.php


推荐阅读