【问题标题】:Correct timezone handling with TYPO3 and Fluid使用 TYPO3 和 Fluid 正确处理时区
【发布时间】:2017-05-09 07:08:56
【问题描述】:
这让我很困惑。我的模型中有一个用 DateTime 注释的属性。在我的数据库中,它存储为时间戳。在前端我使用 f:format.date viewhelper 来输出这个属性。
当我创建新记录并添加 f.e. 01.06.2017 10:00 在此字段中,在我的数据库中存储了 01.06.2017 08:00 的时间戳。在前端输出是正确的。直到这里一切都很好。
3 月的最后一次时间更改导致输出 + 两个小时。我假设在 10 月会再次发生变化,并且输出将比这更多:01.06.2017 08:00。
我该如何防止这种情况发生。当这些日期发生变化时,这绝对是一个问题,因为它对业务很重要。
我如何测试 10 月份会发生什么?
【问题讨论】:
标签:
mysql
datetime
typo3
fluid
【解决方案1】:
问题发生在 TYPO3 将时间标准化为 UTC 时。对于规范化(以及之后的非规范化),它尊重服务器的时区设置。或 LocalConfiguration.php 中给出的设置。
高达 6.2 有两个设置 [SYS][serverTimeZone] 和 [SYS][phpTimeZone]。
对于 7.6,它只有 [SYS][phpTimeZone],因为服务器时区是从 php 本身检测到的。
您现在可以通过将[SYS][phpTimeZone] 设置为字符串“UTC”来将服务器的时区伪装成“UTC”。如此一来,时代就不应再改变了。
【解决方案2】:
TYPO3 9.5 及更新版本
使用环境(documentation)
// use TYPO3\CMS\Core\Utility\GeneralUtility;
// use TYPO3\CMS\Core\Context\Context;
$context = GeneralUtility::makeInstance(Context::class);
// Reading the current data instead of $GLOBALS
$currentTimezone = $context->getPropertyFromAspect('date', 'timezone');
$currentTstamp = $context->getPropertyFromAspect('date', 'timestamp');
$current = new DateTime('@'.$currentTstamp);
$current->setTimezone(new DateTimeZone($currentTimezone) );
在 Fluid 中,您可以使用 DateTime-Object:
// in PHP-ode of Viewhelper
//...
$this->registerArgument('date', 'mixed', 'Either an object implementing DateTimeInterface or a string that is accepted by DateTime constructor');
// ...
在 HTML 中
{dateTimeObject -> f:format.date()}
<f:format.date format="d.m.Y">{dateTimeObject}</f:format.date>