异常未能解析时间字符串

问题描述 投票:1回答:2

我看了几个标题相似的问题,但案子却很不同。我正在尝试使用laravel任务将数据从一个表移动到另一个表。我要从中复制数据的表正在将varchar用于date,而我要复制到的表具有date列类型。因此,在插入新表之前,必须将字符串转换为有效的碳日期。不幸的是,旧表中的日期混合使用不同的格式,因此在插入之前我必须进行检查和转换,但是在处理特定的字符串格式时,我始终会收到此错误]

异常:DateTime :: __ construct():未能分析位置0(2)处的时间字符串(1991年2月26日):意外字符

这是我用于将字符串转换为日期格式的代码,看起来像这样

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的手工艺匠,实际上我可以将字符串转换为日期格式,如下所示enter image description here

为什么我在运行任务时遇到一个特定的字符串时仍然出现错误?

我看了几个标题相似的问题,但案子却很不同。我正在尝试使用laravel任务将数据从一个表移动到另一个表。我要从中复制数据的表...

php laravel php-carbon
2个回答
1
投票

在Carbon中,Carbon::parse('26/02/1991')不支持此格式。碳被认为是('m / d / Y')。这就是为什么当您想解析并转换为toDateString时收到错误。我认为您可以在解析之前更改$dob格式,然后它应该可以工作。


0
投票

我认为失败的人是你

© www.soinside.com 2019 - 2024. All rights reserved.