在 cakephp 的整个项目中使用一种日期格式 3.x

Use one date format in whole project of cakephp 3.x

这可能是一个简单的问题。

有没有什么方法可以在我的项目中只设置一个日期格式,并且在任何地方都使用这种日期格式。我所说的无处不在是指查看、编辑、索引操作。我需要的格式是 Y-m-d H:i:s,它与我的语言环境日期格式无关。

我尝试在 bootstrap 文件中使用以下代码,但没有成功

Type::build('date')->useLocaleParser()->setLocaleFormat('Y-m-d');
Type::build('datetime')->useLocaleParser()->setLocaleFormat('Y-m-d H:i');

在索引中,它一直将日期显示为 10/10/15, 8:20 PM

我还使用文本输入来编辑日期,因此我需要它们在文本框中显示日期 2015/10/10 20:20

我建议您创建一个 file/class 来存放应用程序 CONST 值,然后在您的应用程序 bootstrap 文件中要求 file/autoload class。

define("MYSQL_DATETIME_FORMAT", "Y-m-d H:i:s");

然后,在您的 ApplicationController 中定义一个 属性,例如 $mysql_datetime = MYSQL_DATETIME_FORMAT;,并将此值传递给您的视图、视图助手或装饰器 class。

您还可以创建用户定义或 class 定义的回调(即助手),它使用此值并为您执行转换(例如 function to_mysql_datetime($timeval){...}。然后在您的视图中,您可以打电话:

$formatted_datetime = DateFormatHelper::to_mysql_datetime($other_datetime_value);

这是来自关于此问题的 CakePHP 文档:

If you have any additional configuration needs, you should add them to your application’s config/bootstrap.php file. This file is included before each request, and CLI command.

This file is ideal for a number of common bootstrapping tasks:

Defining convenience functions. Declaring constants. Creating cache configurations. Configuring inflections. Loading configuration files.

Be careful to maintain the MVC software design pattern when you add things to the bootstrap file: it might be tempting to place formatting functions there in order to use them in your controllers. As you’ll see in the Controllers and Views sections there are better ways you add custom logic to your application.

Source

CakePHP 有许多实用程序 类 和关联 helpers 可以为您完成大部分重复性或艰巨的工作。

在这种情况下,Time utility class can take care of formating globally, if you set it up 具有您需要的默认格式。