项目开发过程中有时候需要设置时区以及获取当前时区,步骤如下:
- 设置时区(修改默认的时区)
1.在.env配置时区
APP_TIMEZONE=Asia/Chongqing
2.在config/services.yaml定义配置
parameters:
timezone: '%env(APP_TIMEZONE)%'
3.在Kernel类中覆盖boot方法并从容器中获取时区参数。用date_default_timezone_set函数来设置日期和时间函数所使用的默认时区。
<?php
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
public function boot(): void
{
parent::boot();
date_default_timezone_set($this->getContainer()->getParameter('timezone'));
}
}
- 获取当前时区
<?php
namespace App\Controller;
use DateTime;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class TestController
{
#[Route('/')]
public function index(): Response
{
$now = new DateTime();
return new Response($now->getTimezone()->getName()); // Output: Asia/Chongqing
}
}
