joshbrw/laravel-contextual-dates

Laravel 中的上下文日期功能。

v0.1.4 2017-09-14 14:37 UTC

This package is auto-updated.

Last update: 2024-08-28 22:06:56 UTC


README

安装

  1. 使用 Composer 安装此包: composer require joshbrw/laravel-contextual-dates
  2. 将服务提供者添加到 config/app.phpJoshbrw\LaravelContextualDates\ContextualDatesServiceProvider::class
  3. 使用期望的时区和格式配置 DateTimeFactory。这些格式可以取任何你喜欢的名字,例如 longshort
  4. 使用 FormatsDates 特性或 helpers.php 中定义的辅助函数来本地化/输出日期。

默认值

默认提供两种日期格式,longshort。这些可以在任何时候被覆盖。

示例

使用容器

DateTimeFactory 被绑定为一个单例到容器中,因此它可以随时被获取和修改(类似于 Laravel 提供的内置 View/Validation 工厂)。

$dateTimeFactory = app(DateTimeFactory::class);
$dateTimeFactory->addFormat('mixed', 'Y-m-d');

$carbon = new \Carbon\Carbon;

$dateTime = $dateTimeFactory->createFromCarbon($carbon);

echo $dateTime->format('mixed'); /* Outputs in Y-m-d */

使用辅助函数

此包包含两个辅助方法;localize_date()format_date()

$dateTimeFactory = app(DateTimeFactory::class);
$dateTimeFactory->addFormat('mixed', 'Y-m-d');

$carbon = new \Carbon\Carbon;

$instance = localize_date($carbon); /* Instance of DateTime */

echo format_date($carbon, 'mixed'); /* Outputs in Y-m-d */

使用 Blade 指令

您可以使用 Blade 指令在视图中格式化日期。这实际上是将代理到 format_date() 辅助方法。

@date(new Carbon, 'long')