本文目录导读:

在 Laravel 中设置日期本地化主要涉及以下几个方面:
配置应用语言和时区
修改 config/app.php
'locale' => 'zh-CN', // 设置语言 'faker_locale' => 'zh_CN', // Faker 语言 'timezone' => 'Asia/Shanghai', // 时区
使用 Carbon 进行日期本地化
基础用法
use Carbon\Carbon;
// 设置全局语言
Carbon::setLocale('zh');
// 或使用中文
Carbon::setLocale('zh_CN');
// 示例
$date = Carbon::now();
echo $date->diffForHumans(); // 3分钟前
echo $date->isoFormat('LLLL'); // 2024年1月15日星期一 14:30
在模型中使用访问器
class User extends Model
{
protected $appends = ['formatted_date'];
public function getFormattedDateAttribute()
{
return $this->created_at->isoFormat('YYYY年M月D日');
}
// 或使用 diffForHumans
public function getTimeAgoAttribute()
{
return $this->created_at->diffForHumans();
}
}
创建本地化助手函数
创建 app/helpers.php
<?php
use Carbon\Carbon;
if (!function_exists('format_date')) {
function format_date($date, $format = 'Y年m月d日')
{
if (!$date) return '';
Carbon::setLocale('zh');
return Carbon::parse($date)->translatedFormat($format);
}
}
在 composer.json 中添加:
"autoload": {
"files": [
"app/helpers.php"
]
}
在 Blade 模板中使用
{{ Carbon\Carbon::now()->diffForHumans() }}
{{ $user->created_at->format('Y年m月d日') }}
<!-- 使用自定义格式 -->
{{ $user->created_at->isoFormat('MMMM Do YYYY, h:mm:ss a') }}
创建自定义日期格式化器
创建 Trait
<?php
namespace App\Traits;
use Carbon\Carbon;
trait LocalizedDate
{
public function getLocalizedCreatedAtAttribute()
{
return $this->created_at->isoFormat('Y年M月D日 HH:mm');
}
public function getLocalizedUpdatedAtAttribute()
{
return $this->updated_at->isoFormat('Y年M月D日 HH:mm');
}
}
在模型中使用:
class Post extends Model
{
use LocalizedDate;
}
安装中文语言包
使用 laravel-lang 包
composer require laravel-lang/lang
发布语言文件
php artisan vendor:publish --tag=lang
完整示例
控制器
<?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use App\Models\Post;
class PostController extends Controller
{
public function show(Post $post)
{
Carbon::setLocale('zh');
return view('posts.show', [
'post' => $post,
'formatted_date' => $post->created_at->isoFormat('Y年M月D日 HH:mm'),
'time_ago' => $post->created_at->diffForHumans()
]);
}
}
Blade 视图
<div class="post">
<h2>{{ $post->title }}</h2>
<p>{{ $post->content }}</p>
<small>
发布于:{{ $formatted_date }}
({{ $time_ago }})
</small>
</div>
注意事项
- Carbon 版本:确保 Carbon 版本支持中文(2.x 版本以上)
- 服务器 PHP 环境:需要安装
intl扩展 - 语言文件:自定义验证消息也需要本地化
- JavaScript 前端:如果使用前端渲染,可能需要额外的日期库
这样设置后,你的 Laravel 应用就能正确显示中文格式的日期了。