Carbon设置fr语言后formatLocalized格式化日期仍显示英文问题
问题原因
formatLocalized() 方法底层调用的是操作系统原生的 strftime 函数,依赖系统安装的对应语言 locale 包。你通过 Carbon::setLocale('fr') 设置的是Carbon自身的本地化配置,仅作用于Carbon封装的属性和方法(比如你测试可用的monthName、diffForHumans),不会影响系统级的 locale 设置,所以才会出现两者表现不一致的情况。
解决方法
方法1:换用Carbon原生的本地化格式化方法(推荐,无需修改系统配置)
直接把 formatLocalized 替换为Carbon 2+ 提供的translatedFormat方法,它直接读取Carbon设置的locale,不需要系统安装对应语言包:
public function getHummanCreatedAtAttribute(){ return $this->created_at->translatedFormat('d F Y'); }
也可以用isoFormat方法实现同等效果:
return $this->created_at->isoFormat('DD MMMM YYYY');
方法2:给操作系统安装法语locale包(适合必须使用formatLocalized的场景)
根据你的服务器操作系统执行对应命令安装法语locale:
- Debian/Ubuntu 系列:
sudo locale-gen fr_FR.UTF-8 sudo update-locale
- CentOS/RHEL 系列:
sudo localedef -i fr_FR -f UTF-8 fr_FR.UTF-8
安装完成后重启php-fpm或web服务即可生效。
内容的提问来源于stack exchange,提问作者Michel Gisenäel
相关产品推荐
相关产品推荐

