【发布时间】:2020-05-28 00:03:27
【问题描述】:
我看了几个标题相似的问题,但我的情况却完全不同。我正在尝试使用 laravel 任务将数据从一个表移动到另一个表。我要从中复制数据的表使用varchar 表示date,而我要复制到的表具有date 列类型。因此,在插入新表之前,我必须将字符串转换为有效的碳日期。不幸的是,旧表的日期以不同的格式混合,所以我必须在插入之前检查和转换,但是在处理特定的字符串格式时我不断收到这个错误
异常:DateTime::__construct():无法在位置 0 (2) 解析时间字符串 (26/02/1991):意外字符
这是我将字符串转换为日期格式的代码的样子
if ($user->profile->date_of_birth === null) {
$dob = null;
Log::info([$user->profile->date_of_birth, $dob]);
} else if (Carbon::parse($user->profile->date_of_birth)->toDateString() == true) {
$dob = Carbon::parse($user->profile->date_of_birth)->toDateString();
Log::info([$user->profile->date_of_birth, $dob]);
} else if (Carbon::createFromFormat('d/m/Y', $user->profile->date_of_birth)->format('Y-m-d') == true) {
$formattedDate = Carbon::createFromFormat('d/m/Y', $user->profile->date_of_birth)->format('Y-m-d');
$dob = Carbon::parse($formattedDate)->toDateString();
Log::info([$user->profile->date_of_birth, $dob]);
}
使用 laravel 的 artisan tinker,我实际上可以将字符串转换为日期格式,如下所示
为什么我在运行任务并遇到特定字符串时不断收到错误消息?
【问题讨论】:
标签: php laravel php-carbon