PHP返回日期引发date-fns报错:需用yyyy替代YYYY
日期格式转换与date-fns报错问题
需求与现有代码
我需要将日期输出格式改为13/01/2022,当前PHP代码使用toDateString()格式化日期,完整代码如下:
<?php namespace App\Http\Resources; use App\Models\AssetTimeslot; use Illuminate\Http\Resources\Json\JsonResource; class BookingResource extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable */ public function toArray($request) { return array_merge(parent::toArray($request), [ 'timeslots' => $this->whenLoaded( 'timeslots', fn () => $this->timeslots->map(fn (AssetTimeslot $assetTimeslot) => [ 'id' => $assetTimeslot->id, 'name' => $assetTimeslot->name, 'date' => $assetTimeslot->pivot->date?->toDateString(), 'start_time' => $assetTimeslot->timeslot ? $assetTimeslot->timeslot->start_time : '', 'end_time' => $assetTimeslot->timeslot ? $assetTimeslot->timeslot->end_time : '', ])->groupBy('date') ), ]); } }
错误尝试与报错
我曾尝试以下转换方式:
$orgDate = 'date', $newDate = date("d-m-Y", strtotime($orgDate)), $newDate2 = $newDate . "(dd-MM-yyyy)",
并将日期字段改为'date' => $assetTimeslot->pivot->date?->$newDate2,,但触发了date-fns报错:
react-dom.development.js:12056 Uncaught RangeError: Use yyyy instead of YYYY (in dd-MM-YYYY) for formatting years to the input Wed Mar 22 2023 08:00:00 GMT+0800 (Malaysia Time); see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
我试过包括new Date()在内的多种前端方法,错误依然存在。日期来自日历选择器,控制台显示的日期格式为Wed Mar 22 2023 08:00:00 GMT+0800 (Malaysia Time)。
解决方案
1. PHP端直接输出目标格式
Laravel中Eloquent的日期字段默认是Carbon实例,不需要额外转换,直接调用format()方法输出d/m/Y格式即可:
'date' => $assetTimeslot->pivot->date?->format('d/m/Y'),
这样后端返回的日期就是13/01/2022,前端无需额外处理格式,从根源避免冲突。
2. 修复date-fns的格式模板
如果前端必须处理日期格式,确保使用yyyy(自然年)而非YYYY(周年),将格式化模板改为dd/MM/yyyy,示例如下:
// 正确写法 format(date, 'dd/MM/yyyy')
3. 修正错误的PHP转换逻辑
之前的尝试存在逻辑错误:直接将字符串'date'传给strtotime是无效的,而且不能把变量名当作Carbon实例的属性调用。直接利用Laravel自带的Carbon格式化即可,无需额外处理。
内容的提问来源于stack exchange,提问作者Jabri Juhinin
相关产品推荐
相关产品推荐

