【问题标题】:DateTime::__construct(): Failed to parse time string (from) at position 0 (f): The timezone could not be found in the databaseDateTime::__construct(): 无法在位置 0 (f) 解析时间字符串 (from): 在数据库中找不到时区
【发布时间】:2021-09-25 00:06:09
【问题描述】:

我收到此错误

DateTime::__construct(): 无法在位置 0 (f) 解析时间字符串 (from): 在数据库中找不到时区

我尝试了不同的方法来解决这个错误。但根本没有成功。

$from = null;
$to = null;

try{
    if ($request->input('from') || $request->input('to')) {

        if ($request->input('from')) {
            $from = Carbon::createFromFormat('Y-m-d', $request->input('from'))->toDateString();
        }
        if ($request->input('to')) {
            $to = Carbon::createFromFormat('Y-m-d', $request->input('to'))->toDateString();
        }

        $validator = Validator::make(
            [
                'from' => $from,
                'to'   => $to
            ],
            [
                'from' => 'required|date|date_format:Y-m-d',
                'to'   => 'required|date|date_format:Y-m-d|after_or_equal:from',
            ]
        );
        if ($validator->fails()) {
            return \Redirect::back()
                ->with(array('flash_message' => "Please Enter Correct Date Format"));
        }
    }
} catch (\Exception $e)
{
    \Log::debug("Time invalid ");
}

问题在这里很火,我认为$validator->fails()

有人对此有想法吗?

【问题讨论】:

  • 它不喜欢你的输入。 $request->input('from') 包含什么?尝试Log::info($request->input('from')); 并检查/storage/logs 中的文件
  • 能否请您向我们展示请求值以帮助您解决问题
  • 为什么要在验证前创建 $from 和 $to?您应该先验证,如果有效,那么现在您可以创建它们。
  • 那么,与其捕捉错误并了解发生了什么,不如记录整个异常以供检查:\Log::debug('Time is invalid', ['exception' => $e]);
  • 抱歉,我也不明白Carbon::createFromFormat('Y-m-d', $request->input('from'))->toDateString() 的意思,它基本上是将 Y-m-d 解析为日期对象,然后立即将其重新转换为相同的字符串。

标签: php laravel php-carbon


【解决方案1】:
        // Validate that the strings have a date format
        $validator = Validator::make(
            $request->all(),
            [
                'from' => 'required|date|date_format:Y-m-d',
                'to'   => 'required|date|date_format:Y-m-d|after_or_equal:from',
            ]
        );

        if ($validator->fails()) {
            return \Redirect::back()
                ->with(array('flash_message' => "Please Enter Correct Date Format"));
        }

        // Then after validation, use the string to create date objects
        $from = Carbon::createFromFormat('Y-m-d', $request->input('from'));
        $to = Carbon::createFromFormat('Y-m-d', $request->input('to'));

【讨论】:

    猜你喜欢
    • 2019-09-07
    • 2020-10-16
    • 2021-06-09
    • 2013-06-29
    • 2012-08-08
    • 2022-01-16
    • 1970-01-01
    • 2021-09-12
    相关资源
    最近更新 更多