kibatic/timezone-bundle

用于在正确时区中管理 \DateTimeInterface 的显示。

安装: 395

依赖关系: 0

建议者: 0

安全: 0

星级: 0

关注者: 4

分支: 0

开放问题: 0

类型:symfony-bundle

v2.2.1 2023-06-15 12:52 UTC

This package is auto-updated.

Last update: 2024-09-15 15:46:40 UTC


README

Build Status

此包用于在正确时区中管理 \DateTimeInterface 的显示。

常见情况是一个项目中的所有 \DateTimeInterface 对象都在 UTC(在数据库、在 PHP 中等)中,但用户可以在其偏好设置中更改时区,以便以自己的时区显示日期。

快速入门

安装

composer require kibatic/timezone-bundle

在 config.yml 中

kibatic_timezone:
    default_display_timezone: "Europe/Paris"    # mandatory
    timezone_provider: "App\\Timezone\\MyTimezoneProvider"   # optional

在 PHP 中

/** @var \DateTimeInterface $date */
$date = new \DateTimeImmutable();

$tzAdjuster = $container->get('kibatic_timezone.adjuster');
$dateTimeImmutable = $tzAdjuster->asDateTimeImmutable($date);
$dateTime = $tzAdjuster->asDateTime($date);

使用 AdjusterUtil 将 \DateTime 转换为指定时区

$date = new \DateTime('2019-10-03T15:28:06.256+02:00');
$dateModified = AdjusterUtil::changeTimezone($date, new \DateTimeZone('GMT+0'));

在 twig 中使用时区格式化日期时间

在 twig 中,tzdate 的语法与 twig date filter 的语法完全相同。(它调用默认的日期过滤器。唯一的区别是时区参数默认设置为 false)

{{ date | tzdate }}
{{ date | tzdate('Y/m/d') }}

使用 (intl) 本地化格式化 twig 中的日期时间

您可以使用新的 twig : tz_format_datetime 过滤器。它具有与 twig/extra-bundle 的 format_datetime 过滤器 相同的接口,但默认的 $timezone 设置为 false。

{{ date | tz_format_datetime('short', 'short') }}
{{ date | tz_format_datetime('long', 'long') }}
{{ date | tz_format_datetime }}

弃用的本地化日期

您可以使用新的 twig : tzlocalizeddate 过滤器。它具有与 twig-extension intl 的 localizeddate 过滤器 相同的接口,但默认的 $timezone 设置为 false。

{{ date | tzlocalizeddate('short', 'short') }}
{{ date | tzlocalizeddate('long', 'long') }}
{{ date | tzlocalizeddate }}

时区提供者

时区提供者是实现 TimezoneProviderInterface 的服务。

这是一个用于了解当前显示时区(对于网页、API、命令、导出等)的服务。

它实现了 TimezoneProviderInterface

将调整器作为 twig 全局变量

如果需要,您可以添加调整器作为 twig 全局变量

在 config/packages/twig.yaml 中,您可以添加

twig:
  globals:
    timezoneAdjuster: '@kibatic_timezone.adjuster'

然后在任何 twig 中都可以使用调整器

<div>Timezone : {{ timezoneAdjuster.displayTimezone().name }}</div>

{# convertir un datetime en datetime avec la bone timezone #}
{{ timezoneAdjuster.asDateTime(date) }}

版本

2020-10-16 : v2.1.0

  • 新增:重构:添加 AdjusterUtil 类,允许在不实例化 Adjuster 服务的情况下转换日期时间。
  • 修复:微秒管理。最后一个库从日期时间中移除了微秒。

2020-10-16 : v2.0.0

重大 BC 打破!!

  • 仅适用于 symfony 5.1+
  • 仅适用于 Twig 3+
  • 使用 twig/extra-bundle 而不是 twig/extensions
  • tzlocalizeddate 已弃用。请使用 tz_format_datetime。

2019-10-14 : v1.1.1

  • 嗯...修复 v1.1.0 的 travis 单元测试。

2019-10-14 : v1.1.0

  • 更新了 README。
  • 添加 tzlocalizeddate twig 过滤器

2019-10-11 : v1.0.2

  • 仅适用于 sf4.3+

2019-10-11 : v1.0.1

  • 修复 sf4 的 Configurator 弃用问题

2019-10-11 : v1.0.0

  • 首次发布