grantholle/laravel-timezone

Laravel 用户时区助手。

1.3.0 2024-03-20 16:13 UTC

This package is auto-updated.

Last update: 2024-09-08 10:05:18 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

此包检测并设置用户的时区,并提供一些帮助函数将日期转换为用户的时区。

安装

您可以通过 Composer 安装此包

composer require grantholle/laravel-timezone

您可以使用以下命令发布和运行迁移

php artisan vendor:publish --tag="timezone-migrations"
php artisan migrate

注意 如果您使用多个需要认证的模型,您可能需要在每个模型中添加一个列。

您可以使用以下命令发布配置文件

php artisan vendor:publish --tag="timezone-config"

用法

此包会自动将 timezone 属性设置为登录应用程序的用户。如果 timezone 配置中的 overwite 选项被设置,则每次用户登录时都会进行检查。在底层,此包依赖于 stevebauman/location 包,根据 IP 地址和适当的时区检测用户的位置。在其底层,它依赖于 Laravel 的 request()->ip() 函数,该函数依赖于 Symfony 的 Request 对象以检测 IP 地址。如果您遇到检测错误时区和因此错误的 IP 地址的问题,这可能是由于 受信任代理 配置问题。请查看该文档以获取更多详细信息。

您可以通过更改配置的 events 选项来更改设置时区的活动,或选择退出此功能。

'events' => [
    // By default, the Login event
    \Illuminate\Auth\Events\Login::class,
    // Another event which deals with a user
    \App\Events\MyEvent::class,
],

要忽略此功能,将 events 设置为

除了时区检测之外,您还可以使用一些帮助函数来处理认证用户的日期。

建议的配置

返回日期对象的函数返回 CarbonImmutable 对象。为了节省您很多麻烦,您应该在应用程序中也使用它们。

在您的 AppServiceProvider 的 boot 函数中,

\Illuminate\Support\Facades\Date::use(\Carbon\CarbonImmutable::class);

速查表

以下是一组使用外观和可用帮助函数的示例。

use GrantHolle\Timezone\Facades\Timezone;

// Get the user's or app default timezone
$string = Timezone::getCurrentTimezone();
$string = timezone();

// Get a collection of timezones and a labeled version of them.
// The key is the timezone and the value is a formatted label.
Timezone::timezones();
timezones();

// Convert a date to the user's timezone
// This will return a CarbonImmutable instance
$carbonImmutable = Timezone::toLocal($utcDate);

// Optionally you can pass in a format or use
// the toLocalFormatted function
$string = Timezone::toLocal($utcDate, 'Y-m-d');
$string = to_local_timezone($utcDate, 'Y-m-d');

// Leaving out the last parameter will use the config's `format` value
$string = Timezone::toLocalFormatted($utcDate);
$carbonImmutable = to_local_timezone($utcDate);

// Convert user's dates to your app's timezone.
// It relies on Carbon's `parse` function, so you
// can pass many things to it to parse.
$carbonImmutable = Timezone::fromLocal($usersDate);
$carbonImmutable = from_local_timezone($usersDate);

// Helpers to get the user's "today" and "now" values
$carbonImmutable = Timezone::today();
$carbonImmutable = local_today();
$carbonImmutable = Timezone::now();
$carbonImmutable = local_now();

测试

composer test

更改日志

请参阅 更改日志 了解最近更改的更多信息。

贡献

请参阅 贡献 了解详细信息。

安全漏洞

请参阅 我们的安全策略 了解如何报告安全漏洞。

鸣谢

许可协议

MIT 许可证 (MIT)。请参阅 许可文件 了解更多信息。